怎么用C#获取指定窗口的句柄

时间:2024-10-12 08:38:19

本文介绍如何使用C#获取指定(当前鼠标位置处)窗口的句柄。

怎么用C#获取指定窗口的句柄

工具/原料

Visual Studio(本文使用VS2013,其他版本亦可)。

基础知识

1、获取鼠标位置处窗口句柄,需要使用到Win32Ap坡纠课柩i函数WindowFromPoint,用来根据坐标获取窗口句柄,C#徂葛幢捎引用如下: [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄 public static extern int WindowFromPoint( int xPoint, int yPoint );只要能够获取鼠标的位置,然后调用该函数就可以得到窗口句柄。

2、获取鼠标位置,需要使用鼠标钩子,本文使用已经设计好的鼠标钩子类,关于该类的详细信息见参考资料。

编程实例

1、启动VS,新建C# WinForm项目,如图:

怎么用C#获取指定窗口的句柄

2、引用Win32Api和MouseHook鼠标钩子类,详见参考资料。

3、在Form1中添加4个Label控件,并布局如下:

怎么用C#获取指定窗口的句柄

4、在Form1中添加代码,如下: public partial class Form1 : Form { publi艘早祓胂c Form1() { InitializeComponent(); } MouseHook mh; private void Form1_Load(object sender, EventArgs e) { //安装鼠标钩子 mh = new MouseHook(); mh.SetHook(); mh.MouseMoveEvent += mh_MouseMoveEvent; } void mh_MouseMoveEvent(object sender, MouseEventArgs e) { //当前鼠标位置 int x = e.Location.X; int y = e.Location.Y; lb_p.Text = string.Format("({0},{1})", x, y); int hwnd = Win32Api.WindowFromPoint(x, y);//获取指定坐标处窗口的句柄 lb_h.Text = hwnd.ToString(); } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { mh.UnHook(); } }

5、完成之后,调试运行,结果如下:

怎么用C#获取指定窗口的句柄
© 手抄报圈