在某些应用场合下,我们可能需要在启动A进程启动时关闭进程B。MFC下该如何做呢?以下是我项目中用到的代码:
int KillProcess(DWORD Pid) { //打开进程得到进程句柄 HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,Pid); if(hProcess==NULL) { printf("OpenProcess error "); return 0; } //结束进程 if (TerminateProcess(hProcess,0)) { printf("结束进程成功 "); return 0; } else { printf("结束进程失败 "); 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 ",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进程的代码:
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); }