在DLL中获取主进程窗口句柄
注入到进程之后需要宿主进程的句柄来完成某些动作; 可以采用下列方法来获取宿主进程窗口句柄
1 BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) 2 { 3 DWORD dwCurProcessId = *((DWORD*)lParam); 4 DWORD dwProcessId = 0; 5 6 GetWindowThreadProcessId(hwnd, &dwProcessId); 7 if(dwProcessId == dwCurProcessId && GetParent(hwnd) == NULL) 8 { 9 *((HWND *)lParam) = hwnd; 10 return FALSE; 11 } 12 return TRUE; 13 } 14 15 16 HWND GetMainWindow() 17 { 18 DWORD dwCurrentProcessId = GetCurrentProcessId(); 19 if(!EnumWindows(EnumWindowsProc, (LPARAM)&dwCurrentProcessId)) 20 { 21 return (HWND)dwCurrentProcessId; 22 } 23 return NULL; 24 } 25 26 BOOLEAN WINAPI DllMain( 27 IN HINSTANCE hDllHandle, 28 IN DWORD nReason, 29 IN LPVOID Reserved) 30 { 31 BOOLEAN bSuccess = TRUE; 32 33 switch ( nReason ) 34 { 35 case DLL_PROCESS_ATTACH: 36 MessageBox(GetMainWindow(), TEXT("OMG~ You are Attacked!"), TEXT("Warning"), MB_ICONWARNING); 37 break; 38 39 case DLL_PROCESS_DETACH: 40 break; 41 } 42 43 return bSuccess; 44 }