在某些應用場合下,咱們可能須要在啓動A進程啓動時關閉進程B。MFC下該如何作呢?如下是我項目中用到的代碼:shell
int KillProcess(DWORD Pid) { //打開進程獲得進程句柄 HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,Pid); if(hProcess==NULL) { printf("OpenProcess error\n"); return 0; } //結束進程 if (TerminateProcess(hProcess,0)) { printf("結束進程成功\n"); return 0; } else { printf("結束進程失敗\n"); return 0; } } int GetProcess() { char buff[1024]={0}; PROCESSENTRY32 pe32; pe32.dwSize=sizeof(pe32); //得到系統內全部進程快照 HANDLE hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if(hProcessSnap==INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot error"); return 0; } //枚舉列表中的第一個進程 BOOL bProcess=Process32First(hProcessSnap,&pe32); while(bProcess) { //格式化進程名和進程ID wsprintf(buff,"%s---------------%d\r\n",pe32.szExeFile,pe32.th32ProcessID); //輸出進程名和進程ID printf(buff); memset(buff,0x00,1024); //繼續枚舉進程 bProcess=Process32Next(hProcessSnap,&pe32); } CloseHandle(hProcessSnap); return 0; } bool EnableDebugPrivilege() { HANDLE hToken; LUID sedebugnameValue; TOKEN_PRIVILEGES tkp; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { return FALSE; } if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue)) { CloseHandle(hToken); return false; } tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = sedebugnameValue; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL)) { CloseHandle(hToken); return false; } return true; } void CAngleDetectSystemDlg::CloseSecondSys() { EnableDebugPrivilege(); int rc = 0; HANDLE hSysSnapshot = NULL; PROCESSENTRY32 proc; hSysSnapshot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 ); if ( hSysSnapshot == (HANDLE)-1 ) return; proc.dwSize = sizeof(proc); if ( Process32First ( hSysSnapshot, &proc ) ) { do { if (stricmp(proc.szExeFile, "從機檢測系統.exe") == 0) { HANDLE Proc_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc.th32ProcessID); if (Proc_handle==NULL || !TerminateProcess(Proc_handle, 0)) rc = 1; else rc = 0; } } while ( Process32Next ( hSysSnapshot, &proc ) ); } CloseHandle ( hSysSnapshot ); return; }
其中void CAngleDetectSystemDlg::CloseSecondSys()是關閉進程的函數,「從機檢測系統.exe」是須要關閉的進程,你能夠換成本身須要關閉的進程名稱。注意在關閉其餘進程時,須要提高當前進程的權限。函數
順便附上在A進程中啓動B進程的代碼:ui
void CAngleDetectSystemDlg::OpenSecondSys() { SHELLEXECUTEINFO sys2_shell = {sizeof(sys2_shell)}; sys2_shell.fMask = SEE_MASK_FLAG_DDEWAIT; sys2_shell.lpVerb = "open"; sys2_shell.lpFile = "從機檢測系統.exe"; sys2_shell.nShow = SW_NORMAL; ShellExecuteEx(&sys2_shell); }