#include <Psapi.h> #pragma comment(lib, "Psapi.lib") DWORD FindProcessByName(char *szFindProcessName) { DWORD aProcesses[1024], cbNeeded, cbMneeded; HMODULE hMods[1024]; HANDLE hProcess; char szProcessName[MAX_PATH], *pTmp; int i; if(!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) { return 0; } strlwr(szFindProcessName); for(i=0; i < (int)(cbNeeded/sizeof(DWORD)); i++) { hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,\ FALSE, aProcesses[i]); EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbMneeded); GetModuleFileNameEx(hProcess, hMods[0], szProcessName, sizeof(szProcessName)); strlwr(szProcessName); if((pTmp = strstr(szProcessName, szFindProcessName)) && *(pTmp-1) == '\\') { return aProcesses[i]; } } return 0; } int KillProcessByName(char *strProcessName) { DWORD pid; HANDLE hProcess; pid = FindProcessByName(strProcessName); if(0 == pid) { return -1; } hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); if(NULL == hProcess) { return -2; } TerminateProcess(hProcess,0); CloseHandle(hProcess); return 0; }
还有另一种写法:
#include <TlHelp32.h> DWORD FindProcessByName(char *ProcessName) { HANDLE hHandle; BOOL Next; char szName[MAX_PATH]; PROCESSENTRY32 p32 = {sizeof(p32)}; hHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(INVALID_HANDLE_VALUE == hHandle) { MyDebugPrint("CreateToolhelp32Snapshot failed (%lu)\r\n", GetLastError()); return 0; } Next = Process32First(hHandle, &p32); while (Next) { wsprintf(szName, "%s", p32.szExeFile); if (lstrcmpi(szName, ProcessName) == 0) { return p32.th32ProcessID ; } Next = Process32Next(hHandle, &p32); } CloseHandle(hHandle); return 0; }