bool KillProcess(DWORD pid)
{
// When the all operation fail this function terminate the "winlogon" Process for force exit the system.
HANDLE hYourTargetProcess = OpenProcess(
PROCESS_QUERY_INFORMATION | // Required by Alpha
PROCESS_CREATE_THREAD | // For CreateRemoteThread
PROCESS_VM_OPERATION | // For VirtualAllocEx/VirtualFreeEx
PROCESS_TERMINATE |
PROCESS_VM_WRITE, // For WriteProcessMemory
FALSE, pid);
if(hYourTargetProcess == NULL)
{
return FALSE;
}
if(TerminateProcess(hYourTargetProcess, 0)!=0)
{
::Sleep(150);
return TRUE;
}
else
return FALSE;
}
DWORD CloseProcessIDByName(TCHAR *szProcName)
{
CString str;
DWORD dwProcID = 0;
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
//获取系统中全部进程的快照 Take a snapshot of all processes in the system.
//TH32CS_SNAPPROCESS:在快照中包含系统中所有的进程。
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hProcessSnap)
return(FALSE);
pe32.dwSize = sizeof(PROCESSENTRY32);
// 获取第一个进程的信息 Retrieve information about the first process,
// 若获取失败则退出 and exit if unsuccessful
if (!Process32First(hProcessSnap, &pe32))
{
// 清除快照 clean the snapshot object
CloseHandle(hProcessSnap);
str.Format( "! Failed to gather information on system processes! \n");
OutputDebugString(str);
return(NULL);
}
//匹配进程ID Matching Process ID
do
{
if (!strcmp(szProcName,pe32.szExeFile))
{
//拷贝进程名 Copy Process Name
str.Format("%s:%d \n", pe32.szExeFile , pe32.th32ProcessID );
OutputDebugString(str);
KillProcess(pe32.th32ProcessID);//test
dwProcID = pe32.th32ProcessID;
}
//cout << pe32.szExeFile << endl;
} while (Process32Next(hProcessSnap, &pe32));
// 清除快照 clean the snapshot object
CloseHandle(hProcessSnap);
return dwProcID;
}
用例:
//采用头文件#include <TlHelp32.h>
//注意某些进程若终结失败,需要你的exe提升到管理员权限来运行才能.
CloseProcessIDByName("chrome.exe"); //关闭全部谷歌浏览器chorme.exe