通过C#API函数获取窗体句柄。以下四个API函数都为【DllImport("user32.dll")】动态链接库
工具/原料
publicstaticexternintGetCursorPos(refPointAPIlpPoint)//获取鼠标坐标,该坐标是光标所在的屏幕坐标位置
publicstaticexternintWindowFromPoint(intxPoint,intyPoint);//指定坐标处窗体句柄
publicstaticexternintGetWind艺皱麾酪owText(inthwnd,StringBuilderlpString,intnMaxCount);//获取窗体标题名称
publicstaticexternintGetClassName(inthwnd,StringBuilderlpstring,intnMaxCount);//获取窗体类名称
方法/步骤
1、打开VS,创建如图一个窗体,再加入一个定时器控件Timer
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、运行后,光标所在位置即可显示当前所在窗体的句柄名称,句柄类名称。有了句柄就可以做很多事情!