轉載請注明來源:https://www.cnblogs.com/hookjc/
#inclucde <Psapi.h>
#param comment(lib,"Psapi.lib")
DWORD CGetWindowDlg::FindProcess(char *strProcessName)
{
DWORD aProcesses[1024], cbNeeded, cbMNeeded;
HMODULE hMods[1024];
HANDLE hProcess;
char szProcessName[MAX_PATH];
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return 0;
for(int 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));
CString szName=szProcessName;
CString strName=strProcessName;
szName=szName.Right(strName.GetLength()+1);
szName.MakeLower();
strName.MakeLower();
if(szName=="\\"+strName)
{
return(aProcesses[i]);//0x0109ed98
}
}
return 0;
}
HWND CGetWindowDlg::GetWindowHandleByPID(DWORD dwProcessID)//通過進程ID獲取頂層窗口句柄
{
HWND h = ::GetTopWindow(0);
while (h)
{
DWORD pid = 0;
DWORD dwTheardId = GetWindowThreadProcessId( h,&pid);
if (dwTheardId != 0)
{
if ( pid == dwProcessID/*your process id*/ )
{
// here h is the handle to the window
while (::GetParent(h)!=NULL)
h=::GetParent(h);
return h;
}
}
h = ::GetNextWindow(h, GW_HWNDNEXT);
}
return NULL;
}