在DLL中获取主进程窗口句柄

有的时候难免需要在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

转载于:https://my.oschina.net/u/2314763/blog/422621

在Windows窗体应用程序(WinForm),你可以使用Win32 API函数来获取当前进程的窗口句柄。最常用的方法是使用`GetCurrentProcess`和`GetWindowThreadProcessId`函数组合,然后再使用`GetShellWindow`来获取窗口句柄,或者使用`FindWindow`来获取指定类名或窗口名的窗口句柄。 以下是一个示例代码,展示了如何获取当前WinForm应用程序的主窗口句柄: ```csharp using System; using System.Runtime.InteropServices; public class NativeMethods { // 获取当前进程的句柄 [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess(); // 获取与指定进程句柄相关联的线程ID [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); // 获取当前应用程序的主窗口句柄 [DllImport("user32.dll")] public static extern IntPtr GetShellWindow(); } class Program { static void Main() { // 获取当前进程的ID int processId; IntPtr currentProcess = NativeMethods.GetCurrentProcess(); NativeMethods.GetWindowThreadProcessId(NativeMethods.GetShellWindow(), out processId); // 检查当前进程ID是否与我们的进程ID相同 if (processId == System.Diagnostics.Process.GetCurrentProcess().Id) { IntPtr shellWindow = NativeMethods.GetShellWindow(); // 此处可以使用shellWindow句柄进行后续操作,例如显示窗口等 } } } ``` 在这个代码,`NativeMethods`类包含了一些必要的Win32 API函数的声明,`GetShellWindow`函数返回了当前应用程序的主窗口句柄,然后我们通过`GetWindowThreadProcessId`函数确认这个窗口句柄是否属于当前进程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值