有的时候难免需要在DLL中获取主进程的窗口句柄,比如在DLL注入的时候等等。那么如何在DLL中获取主进程的窗口句柄呢?可以通过EnumWindows来实现。先通过GetCurrentProcessId获取进程的PID,然后在EnumWindows中调用GetWindowThreadProcessId获得与窗口句柄关联的进程PID,然后对比PID,看是否相等,并判断是不是主窗口即可。
#include <windows.h>
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD dwCurProcessId = *((DWORD*)lParam);
DWORD dwProcessId = 0;
GetWindowThreadProcessId(hwnd, &dwProcessId);
if(dwProcessId == dwCurProcessId && GetParent(hwnd) == NULL)
{
*((HWND *)lParam) = hwnd;
return FALSE;
}
return TRUE;
}
HWND GetMainWindow()
{
DWORD dwCurrentProcessId = GetCurrentProcessId();
if(!EnumWindows(EnumWindowsProc, (LPARAM)&dwCurrentProcessId))
{
return (HWND)dwCurrentProcessId;
}
return NULL;
}
BOOLEAN WINAPI DllMain(
IN HINSTANCE hDllHandle,
IN DWORD nReason,
IN LPVOID Reserved)
{
BOOLEAN bSuccess = TRUE;
switch ( nReason )
{
case DLL_PROCESS_ATTACH:
MessageBox(GetMainWindow(), TEXT("OMG~ You are Attacked!"), TEXT("Warning"), MB_ICONWARNING);
break;
case DLL_PROCESS_DETACH:
break;
}
return bSuccess;
}
Copyed From 程序人生
Home Page:http://www.programlife.net
Source URL:http://www.programlife.net/get-main-window-handler-in-dll.html