C# 获取指定进程的主窗口句柄

静态方法,直接上代码吧:

 1 using System;
 2 using System.Runtime.InteropServices;
 3 
 4 namespace Macroresolute
 5 {
 6     public static class ProcessEx
 7     {
 8         private static class NativeMethods
 9         {
10             internal const uint GW_OWNER = 4;
11 
12             internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
13 
14             [DllImport("User32.dll", CharSet = CharSet.Auto)]
15             internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
16 
17             [DllImport("User32.dll", CharSet = CharSet.Auto)]
18             internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
19 
20             [DllImport("User32.dll", CharSet = CharSet.Auto)]
21             internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
22 
23             [DllImport("User32.dll", CharSet = CharSet.Auto)]
24             internal static extern bool IsWindowVisible(IntPtr hWnd);
25         }
26 
27         public static IntPtr GetMainWindowHandle(int processId)
28         {
29             IntPtr MainWindowHandle = IntPtr.Zero;
30 
31             NativeMethods.EnumWindows(new NativeMethods.EnumWindowsProc((hWnd, lParam) =>
32             {
33                 IntPtr PID;
34                 NativeMethods.GetWindowThreadProcessId(hWnd, out PID);
35 
36                 if (PID == lParam &&
37                     NativeMethods.IsWindowVisible(hWnd) &&
38                     NativeMethods.GetWindow(hWnd, NativeMethods.GW_OWNER) == IntPtr.Zero)
39                 {
40                     MainWindowHandle = hWnd;
41                     return false;
42                 }
43 
44                 return true;
45 
46             }), new IntPtr(processId));
47 
48             return MainWindowHandle;
49         }
50     }
51 }
52

 

转载于:https://www.cnblogs.com/zys529/archive/2012/04/25/2470039.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值