1. system方法: 原型:
int __cdecl system(const char *);
例如:
system("ipconfig");
2. WinExec方法: 相比於system方法,WinExec方法多了一個視窗參數:
原型:
UINT WinExec( LPCSTR lpCmdLine, UINT uCmdShow);
例如:
WinExec("ipconfig", SW_SHOW); 參數可以是:SW_SHOW,,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED等等,總體用法是差不多的。
3. ShellExecute方法: 這個方法主要用於open,edit,find等方法的操作:
原型:
HINSTANCE ShellExecute( HWND hwnd, LPCTSTR lpOperation, LPCTSTR lpFile, LPCTSTR lpParameters, LPCTSTR lpDirectory, INT nShowCmd);
例如:
ShellExecute(NULL,"open","abc.xls",NULL,NULL,SW_HIDE);//開啟預設路徑的abc.xls檔案
4.可回顯的調用方法: 這個方法步驟比較複雜,是通過建立一個新進程來類比cmd命令列,將寫命令列和回顯通過管道的方式呈現。
例如:
void CTestMFCDlg::OnOK() { // TODO: Add extra validation here SECURITY_ATTRIBUTES sa; HANDLE hRead,hWrite; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if(!CreatePipe(&hRead,&hWrite,&sa,0)) { MessageBox("CreatePipe Failed"); return; } STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; si.hStdOutput = hWrite; si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; char cmdline[200]; CString tmp,stredit2; GetDlgItemText(IDC_EDIT_CMD,stredit2); tmp.Format("cmd /C %s",stredit2); sprintf(cmdline,"%s",tmp); if(!CreateProcess(NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) { MessageBox("CreateProcess failed!"); return; } CloseHandle(hWrite); char buffer[4096] = {0}; CString strOutput; DWORD bytesRead; while(1) { if(NULL == ReadFile(hRead,buffer,4095,&bytesRead,NULL)) { break; } strOutput += buffer; SetDlgItemText(IDC_EDIT_TEXT,strOutput); UpdateWindow(); Sleep(1000); } CloseHandle(hRead);}以上是在一個MFC中點擊OnOK按鈕後,將IDC_EDIT_CMD編輯框中的命令執行,並將1秒內cmd命令的回顯答應到IDC_EDIT_TEXT編輯框中的實現。