process 管理中,PID 取得是第一步且重要的事,這裡提出二、三種方式取得 process ID
1. 已知視窗名稱
DWORD GetPIDByWindowName(const char* ClassName, const char* WindowName)
{
DWORD PID;
HWND targetWnd = FindWindow(ClassName, WindowName);
GetWindowThreadProcessId(targetWnd, &PID);
return PID;
}
2. 已知執行程式名稱
DWORD GetPIDByExecuteName(const char* ProcessName)
{
PROCESSENTRY32 Entry;
HANDLE hSnapShot;
DWORD PID;
BOOL ret;
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapShot==INVALID_HANDLE_VALUE){
printf("CreateToolhelp32Snapshot fail.\n");
return -1;
}
Entry.dwSize = sizeof(PROCESSENTRY32);
ret = Process32First(hSnapShot, &Entry);
while(ret){
if(!stricmp(Entry.szExeFile, ProcessName)){
break;
}
ret = Process32Next(hSnapShot, &Entry);
}
CloseHandle(hSnapShot);
return Entry.th32ProcessID;
}
3. 取得程式本身之 PID
DWORD Pid = GetCurrentProcessId();