1. system方法:
原型:
[cpp] view plain copy
- int __cdecl system(const char *);
例如:
[cpp] view plain copy
- system("ipconfig");
2. WinExec方法:
相比于system方法,WinExec方法多了一个窗口参数:
原型:
[cpp] view plain copy
- UINT WinExec(
- LPCSTR lpCmdLine,
- UINT uCmdShow
- );
例如:
WinExec("ipconfig", SW_SHOW);
参数可以是:SW_SHOW,,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED等等,总体用法是差不多的。
3. ShellExecute方法:
这个方法主要用于open,edit,find等方法的操作:
原型:
[cpp] view plain copy
- HINSTANCE ShellExecute(
- HWND hwnd,
- LPCTSTR lpOperation,
- LPCTSTR lpFile,
- LPCTSTR lpParameters,
- LPCTSTR lpDirectory,
- INT nShowCmd
- );
例如:
[cpp] view plain copy
- ShellExecute(NULL,"open","abc.xls",NULL,NULL,SW_HIDE);//打开默认路径的abc.xls文件
4.可回显的调用方法:
这个方法步骤比较复杂,是通过创建一个新进程来模拟cmd命令行,将写命令行和回显通过管道的方式呈现。
例如:
[cpp] view plain copy
- 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编辑框中的实现
时间: 2024-10-14 00:48:54