在DLL中獲取主程序視窗控制代碼
阿新 • • 發佈:2019-02-09
有的時候難免需要在DLL中獲取主程序的視窗控制代碼,比如在DLL注入的時候等等。那麼如何在DLL中獲取主程序的視窗控制代碼呢?可以通過EnumWindows來實現。先通過GetCurrentProcessId獲取程序的PID,然後在EnumWindows中呼叫GetWindowThreadProcessId獲得與視窗控制代碼關聯的程序PID,然後對比PID,看是否相等,並判斷是不是主視窗即可。
以上方法參考自網路,不一定很完善,但是通常情況下已經夠用了。附上測試程式碼:
以上方法參考自網路,不一定很完善,但是通常情況下已經夠用了。附上測試程式碼:
// Author: 程式碼瘋子 // Blog: http://www.programlife.net/ #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; }