Recently I learned some windows related programming and needed to obtain some form handles. So I checked some documents online and found that the form handles were mainly completed through three functions of USER32:
Windowfrompoint returns a window handle.
GetwindowtextGet window title
GetclassnameGet class name
The following is the implementation process
Create a project: gethandle
Add a button, Textbox, and Timer control.
BackgroundCodeAs follows:
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. DaTa;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;
Using system. runtime. interopservices;
Namespace gethandle
{
Public partial class form1: Form
{
// Obtain the window title
[Dllimp ORT ("USER32", setlasterror = true)]
Public static extern int getwindowtext (
Intptr hwnd, // window handle
Stringbuilder lpstring, // Title
Int nmaxcount // maximum value
);
// Obtain the class name
[Dllimp ORT ("user32.dll")]
Private Static extern int getclassname (
Intptr hwnd, // handle
Stringbuilder lpstring, // Class Name
Int nmaxcount // maximum value
);
// Obtain the window Handle Based on coordinates
[Dllimp ORT ("USER32")]
Private Static extern intptr windowfrompoint (
Point point // coordinates
);
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Timer1.enabled =! Timer1.enabled;
}
Private void timereffectick (Object sender, eventargs E)
{
Int x = cursor. position. X;
Int y = cursor. position. Y;
Point P = new point (x, y );
Intptr formhandle = windowfrompoint (p); // obtain the window handle
Stringbuilder Title = new stringbuilder (256 );
Getwindowtext (formhandle, title, title. capacity); // obtain the title of the window.
Stringbuilder classname = new stringbuilder (256 );
Getclassname (formhandle, classname, classname. capacity); // get the window handle
This. textbox1.text = "window handle:" + formhandle. tostring () + environment. newline + "window title:" + title + environment. newline + "Class Name:" + classname;
}
Private void textbox1_keydown (Object sender, keyeventargs E)
{
If (E. keycode = keys. Enter | E. keycode = keys. Space)
{
This. button1.w.mclick ();
}
}
}
}
In fact, these methods mainly refer to the methods on the mysterious pig blog. Address: Ghost