//----------------------------------------------------新建进程任务
//点击 "新建任务"按钮 代码如下:
//打开新建任务对话框void CProp_Process::OnClickedBtnNewProcess(){ CNewProcess *newProcess = new CNewProcess(); //CNewProcess 为一个CDlgEx类型的对话框类 newProcess->Create(IDD_DIALOG_NEW_PROCESS,this); //IDD_DIALOG_NEW_PROCESS为对话框的资源ID newProcess->ShowWindow(SW_SHOW); }将打开如下图的对话框
//确定 按钮 新建任务void CNewProcess::OnBnClickedNewProcess(){ WCHAR pszExeName[MAX_PATH]={0}; GetDlgItemText(IDC_COMBO_CREATE_PROCESS,pszExeName,MAX_PATH);//获得组合框中输入的路径 //IDC_COMBO_CREATE_PROCESS 为图中组合键的资源ID int codeIndex=CreateNewProcess(pszExeName);//新建任务 调用下面的函数,传入的参数是新建任务(.exe)的完整路径 //判断是否成功新建进程 CString strWrongPath; strWrongPath.Format(_T("windows 找不到文件' %s ',请确定文件是否正确后,再试一次!"),pszExeName); if(codeIndex==0) { AfxMessageBox(strWrongPath); }}
//新建任务int CNewProcess::CreateNewProcess(WCHAR pszExeName[]) { //结构体 PROCESS_INFORMATION piProcInfoGPS; STARTUPINFO siStartupInfo; SECURITY_ATTRIBUTES saProcess, saThread; //初始化结构体 ZeroMemory( &siStartupInfo, sizeof(siStartupInfo) ); siStartupInfo.cb = sizeof(siStartupInfo); saProcess.nLength = sizeof(saProcess); saProcess.lpSecurityDescriptor = NULL; saProcess.bInheritHandle = true; saThread.nLength = sizeof(saThread); saThread.lpSecurityDescriptor = NULL; saThread.bInheritHandle = true; //创建进程 int isSuccess = ::CreateProcess( NULL, (LPTSTR)pszExeName, &saProcess,&saThread, false, CREATE_DEFAULT_ERROR_MODE,NULL,NULL, &siStartupInfo, &piProcInfoGPS ); return isSuccess;}
//浏览 打开对话框获得进程路径void CNewProcess::OnClickedView(){ // TODO: Add your control notification handler code here CFileDialog fileDlg(TRUE); fileDlg.m_ofn.lpstrTitle=_T("打开文件"); fileDlg.m_ofn.lpstrFilter=_T("Program(*.exe)\0*.exe\0All Files(*.*)\0*.*\0\0");//过滤exe后缀文件 if(IDOK==fileDlg.DoModal()) { LPWSTR pszExeName=fileDlg.m_ofn.lpstrFile;//获得进程完整路径 //CString pszExeName1=fileDlg.GetFileName(); //CString pszExeName =fileDlg.GetFolderPath(); SetDlgItemText(IDC_COMBO_CREATE_PROCESS,pszExeName);//把路径设置到编辑框中 IDC_COMBO_CREATE_PROCESS为组合控件ID int codeIndex=CreateNewProcess(pszExeName); //判断是否成功新建进程 CString strWrongPath; strWrongPath.Format(_T("windows 找不到文件' %s ',请确定文件是否正确后,再试一次!"),pszExeName); if(codeIndex==0) { AfxMessageBox(strWrongPath); } } }//---------------------------------------------------------- 结束进程(因为 Win系统权限的问题,所以有的系统进程不能结束) 代码如下
void EndOfProcess(DWORD PID){ HANDLE hProcess; BOOL isEnd; //PID为进程ID if(szBuf!=NULL) { hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,PID);//获取进程句柄 if(hProcess==NULL) { DWORD dwError=GetLastError(); CString strError; strError.Format(_T("获取句柄失败,Error Code is: %d"),dwError); MessageBox(strError); } isEnd=TerminateProcess(hProcess,0);//判断进程是否成功结束 if(isEnd) { MessageBox(_T("进程结束")); }else { MessageBox(_T("进程结束失败")); } CloseHandle(hProcess);}
版权声明:本文为博主原创文章,未经博主允许不得转载。