养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

C#获取目标窗体句柄

时间:2024-11-03 00:38:36

通过C#API函数获取窗体句柄。以下四个API函数都为【DllImport("user32.dll")】动态链接库

工具/原料

publicstaticexternintGetCursorPos(refPointAPIlpPoint)//获取鼠标坐标,该坐标是光标所在的屏幕坐标位置

publicstaticexternintWindowFromPoint(intxPoint,intyPoint);//指定坐标处窗体句柄

publicstaticexternintGetWind艺皱麾酪owText(inthwnd,StringBuilderlpString,intnMaxCount);//获取窗体标题名称

publicstaticexternintGetClassName(inthwnd,StringBuilderlpstring,intnMaxCount);//获取窗体类名称

方法/步骤

1、打开VS,创建如图一个窗体,再加入一个定时器控件Timer

C#获取目标窗体句柄

2、引入:usingSystem.Runtime.InteropServices;命名空间然后全部代码如下。

3、[DllImport("user32.dll")]publics隋茚粟胫taticexternintGetCurso鸡堕樱陨rPos(refPointAPIlpPoint);//获取鼠标坐标,该坐标是光标所在的屏幕坐标位置[DllImport("user32.dll")]publicstaticexternintWindowFromPoint(intxPoint,intyPoint);//指定坐标处窗体句柄[DllImport("user32.dll")]publicstaticexternintGetWindowText(inthwnd,StringBuilderlpString,intnMaxCount);//获取窗体标题名称[DllImport("user32.dll")]publicstaticexternintGetClassName(inthwnd,StringBuilderlpstring,intnMaxCount);//获取窗体类名称[StructLayout(LayoutKind.Sequential)]publicstructPointAPI{publicintx;publicinty;}boolbt=false;privatevoidbutton1_Click(objectsender,EventArgse){if(!bt){this.button1.Text="关闭";timer1.Enabled=true;timer1.Start();bt=true;}else{this.button1.Text="开启";timer1.Enabled=false;timer1.Stop();bt=false;}}PointAPIpi=newPointAPI();publicvoidPointA(){GetCursorPos(refpi);inthwnd=WindowFromPoint(pi.x,pi.y);StringBuildername=newStringBuilder(255);StringBuilderclassName=newStringBuilder(255);GetWindowText(hwnd,name,255);GetClassName(hwnd,className,255);textBox1.Text=name.ToString();textBox2.Text=className.ToString();}privatevoidForm1_Load(objectsender,EventArgse){timer1.Enabled=false;timer1.Stop();}privatevoidtimer1_Tick(objectsender,EventArgse){PointA();}}

4、运行后,光标所在位置即可显示当前所在窗体的句柄名称,句柄类名称。有了句柄就可以做很多事情!

© 一点知识