如果只要判斷EXE的名字(不需要判斷路徑),可以省略EnumProcess,因為pe32.szExeFile 裡就已經有EXE的名字了,因為沒有路徑,所以才又使用了函數EnumProcess來取得完整的路徑。這樣就簡潔一些了。
BOOL CALLBACK EnumWinProc(HWND hwnd, LPARAM lParam)
{
DWORD dwID;
GetWindowThreadProcessId(hwnd, &dwID);
if (dwID == (DWORD)lParam) {
PostMessage(hwnd, WM_QUIT, 0, 0);
return FALSE;
}
return TRUE;
}
void KillProgram(LPCSTR ExeName)
{
char *File;
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
if (!ExeName || !ExeName[0])
return;
File = strrchr(ExeName, '\\');
if (File!=0) ExeName = File+1;
hProcessSnap = CreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == (HANDLE)-1) return;
memset(&pe32, 0, sizeof(pe32));
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hProcessSnap, &pe32))
{
do {
memset(&me32, 0, sizeof(me32));
me32.dwSize = sizeof(me32);
File = strrchr(pe32.szExeFile, '\\');
File = File? File+1 : pe32.szExeFile;
if (strcmpi(File,ExeName)==0) {
EnumWindows((WNDENUMPROC)EnumWinProc,
pe32.th32ProcessID);
}
}
while(Process32Next(hProcessSnap,&pe32));
}
CloseHandle(hProcessSnap);
}