C # form common API Function Application Form search,

Source: Internet
Author: User

C # form common API Function Application Form search,

The API functions used to process forms are as follows (note: the API functions must be placed in the form ...):

To reference DllImport in C #, you must add the using System. Runtime. InteropServices namespace.

(1) obtain the current front-end form handle

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]public static extern IntPtr GetForegroundWindow();

The return value type is IntPtr, which is the handle of the current obtained focus window.

Usage:

IntPtr myPtr=GetForegroundWindow();

(2) enumerate top-level windows on all screens and send the window handle to the callback function defined by the application. This method can be used to obtain the handle information of all currently opened forms.

[DllImport("user32.dll")]public static extern  bool EnumWindows(WNDENUMPROC lpEnumFunc,LPARAM lParam);

LpEnumFunc points to the callback function pointer defined by an application;

Lparam points to the defined value of an application passed to the callback function;

Callback function prototype

bool CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lparam);

Hwnd is the handle of a top-level window.

Lparam is a value defined by an application (that is, lParam in EnumWindows)

The following is an example to illustrate this method.

The program needs to implement a function: you can find the target form in the currently opened form, and activate it as needed, set it to the foreground form

Using System; using System. collections. generic; using System. linq; using System. text; using System. runtime. interopServices; // call DLLIMPORTnamespace EmuWindowInfor {// <summary> // call API's EnumWindows to enumerate the window // </summary> class Program {// define the public global variable of the handle int HANDLE; // define the delegate public delegate bool CALLBACK (int hwnd, int lparm) of the CALLBACK function; // gets the foreground window handle and sets the current window handle [DllImport ("user32.dll")] public static extern int Enum Windows (CALLBACK x, int y); [DllImport ("user32.dll", CharSet = CharSet. auto)] static extern int GetWindowText (int hWnd, StringBuilder lpText, int nCount); static void Main (string [] args) {CALLBACK myCallBack = new CALLBACK (Report ); enumWindows (myCallBack, 0); Console. readKey ();} // instantiate the callback function (you can find the target form Handle Based on the form name in the callback function) public static bool Report (int hwnd, int lparm) {// allocate space var sb = new StringBuilder (50 ); GetWindowText (hwnd, sb, sb. Capacity); // note that some windows do not have the title if (sb. ToString ()! = String. empty) Console. writeLine (sb. toString (); // if (sb. toString () = "Microsoft PowerPoint-[les_03 _ use _ rman [compatible mode]") // Console. writeLine (hwnd. toString (); // The callback function returns true ;}}}

The above code finds the handle of the target form through the form name, and uses the API function SetForegroundWindow to activate the form and

[DllImport("user32.dll")]public static extern bool SetForegroundWindow(int hWnd);

HWnd is the handle of the target form.

(3) obtain the target form based on the class name and window name of the form.

[DllImport("coredll.dll", EntryPoint = "FindWindow")]private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

If coredll. dll cannot be found, use user32.dll instead.

[DllImport("user32.dll", EntryPoint = "FindWindow")]private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

Here, the lpClassName is the class of the window to be found.

LpWindowName is the title of the window to be searched. Of course, you do not need to know either of them, but at least you need to know one. Window title search is generally used in multi-window applications, because the form title in the program is fixed, easy to search. However, for some forms in the system, such as Notepad and PPT, the title of the form is not fixed, so it is more convenient to use window-type search. Of course, common window classes can be easily found. Below is a code to search for the window handle currently opened in text documents.

IntPtr ParenthWnd = new IntPtr (0); ParenthWnd = FindWindow (null, "window title"); // or use ParenthWnd = FindWindow ("window class name", null ); // determine whether the form is valid if (ParenthWnd! = IntPtr. Zero) {MessageBox. Show ("find window");} else {MessageBox. Show ("no window found ");}

You can use the accexplorer32.exe tool to find the class and form title of the window.

If you use the VC development platform, you can use Spy to quickly find the window type. In Spy ++, there is a FindWindow tool that allows you to select a window with the mouse, then Spy ++ will display the class of this window.

At the same time in Microsoft's help documentation also gives the common Microsoft OFFICE Tool Form handle to find the method, also use FindWindow () method, link: http://support.microsoft.com/kb/302295/zh-cn

(4) method for searching subforms

[DllImport("user32.dll", EntryPoint = "FindWindow")]private static extern IntPtr FindWindowEx( IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow );

HwndParent is the parent window handle of the Child Window. If hwndParent is Null, the function uses the desktop window as the parent window to find all the child windows of the desktop window. If hwndParent is HWND_MESSAGE, the function only finds all message windows;

HwndChildAfter: the sub-window handle. The query starts from the next subwindow In the Z-order. The child window must be a direct Child Window of the hwndPareRt window, rather than a child window. If HwndChildAfter is NULL, search starts from the first subwindow of hwndParent. If both hwndParent and hwndChildAfter are NULL, the function searches for all top-level windows and message windows.

LpszClass: a pointer to an empty ending string that specifies the class name or a member that identifies the class name string. If this parameter is a member, it must be a global member generated by the previous call to the theGlobaIAddAtom function. This member is 16 bits, must be at the low 16 bits of the lpClassName, and the high bits must be 0.

LpszWindow: point to an empty ending string that specifies the window name (window title. If this parameter is NULL, all windows are matched. Return Value: If the function succeeds, the return value is a window handle with the specified class name and window name. If the function fails, the return value is NULL. In short, this function searches for subwindows, starting from the next subwindow after the given subwindow. The search result is case insensitive.

The following is a simple example to illustrate the subwindow search. I believe everyone has a QQ number, so I will write a simple plug-in: Find the QQ login window and simulate the buttons to achieve automatic login of QQ. The following is only an introduction to how to find the child form through the parent form

Const int BM_CLICK = 0xF5; IntPtr maindHwnd = FindWindow (null, "QQ User Logon"); // obtain the QQ login box handle if (maindHwnd! = IntPtr. Zero) {IntPtr childHwnd = find1_wex (maindHwnd, IntPtr. Zero, null, "login"); // obtain the button handle if (childHwnd! = IntPtr. zero) {SendMessage (childHwnd, BM_CLICK, 0, 0); // send the message of the click button} else {MessageBox. show ("subwindow not found") ;}} else {MessageBox. show ("no window found ");}

(5) Find the form and perform simple operations on it, such as switching and hiding

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

ShowWindow (IntPtr hwnd, int nCmdShow );

Meaning of nCmdShow

0 hide window

1 normal size display window

2. Minimize the window

3. maximized window

(6) obtain the window size and position

[DllImport ("user32.dll")] [return: financialas (UnmanagedType. bool)] static extern bool GetWindowRect (IntPtr hWnd, ref RECT lpRect); [StructLayout (LayoutKind. sequential)] public struct RECT {public int Left; // The leftmost coordinate public int Top; // the rightmost coordinate public int Right; // the rightmost coordinate public int Bottom; // bottom coordinate} example: InPtr awin = GetForegroundWindow (); // obtain the current window handle RECT rect = new RECT (); GetWindowRect (awin, ref rect ); int width = rc. right-rc. left; // The window width int height = rc. bottom-rc. top; // The window height int x = rc. left; int y = rc. top;

(7) Common Operations:

GetClassName (hWnd: HWND; {specified window handle} lpClassName: PChar; {buffer} nMaxCount: Integer {buffer size}): Integer; {returned class name size; failed to return 0} Get the Class Name of the specified window GetNextWindow (hWnd: HWND; {the specified window handle} uCmd: UINT {the specified link option}): HWND; {0 is returned for failure; return the matched window handle} // uCmd. Optional values: GW_HWNDNEXT = 2; {in Z order of the same level} GW_HWNDPREV = 3; {above the same level Z sequence} obtains the GetTopWindow (hWnd: HWND; {specified window handle}) of the window on the specified Z or Z in the same level. {0 is returned for failure; return the top-level sub-window handle}. Obtain the top-level sub-window handle GetWindow (hWnd: HWND; {specified window handle} uCmd: UINT {specified link options}): HWND; {0 is returned for failure; a qualified window handle is returned for success} // optional uCmd value: GW_HWNDFIRST = 0; {first at the same level} GW_HWNDLAST = 1; {last at the same level} GW_HWNDNEXT = 2; {next at the same level} GW_HWNDPREV = 3; {last at the same level} GW_OWNER = 4; {Main Window} GW_CHILD = 5; {subwindow}: Integer; {return window title length} get window title length SetWindowText (hWnd: HWND; {window handle} lpString: PChar {New title string pointer}): BOOL; set window title getwindowtopwindow: HWND; {No parameter; return the handle of the desktop window}

As mentioned above, after finding the target handle, you can use the SetForeGroudWindow (int hwnd) method to activate it and set it to the foreground window, however, if you only want to activate it without setting it as the foreground, you need to use the SetActiveWindow () function ()

However, you must note that this method does not work when activating the current thread form in other threads.

To make the target form and other forms appear on the desktop at the same time, make sure that only the target form is active, that is to say, only the target form can receive the analog button message. Finally, you can use the SetForwardWindow (int handle) method to activate the target form and put it in the front form. At the same time, use another API function SetWindowPos to set other forms so that they can be at the same desktop. This method is briefly introduced below:

Static extern bool SetWindowPos (HWND hWnd, // window handle HWND hWndInsertAfter, // handle int X, // horizontal coordinate int Y, // vertical coordinate int cx, // wide int cy, // high UINT uFlags // window positioning identifier );

Where

Return Value:

BOOL. If the returned value is non-zero, the return value is successful. If the returned value is zero, the return value is failed. For error information, see the GetLastError function.

Parameter table:

Parameter type and description
Hwnd HWND, the window handle to be located
HWndInsertAfter HWND: The Window handle placed before hwnd. This parameter must be a window handle or one of the following values: HWND_BOTTOM puts the window at the bottom of all other windows
HWND_NOTOPMOST places the window at the top of all other windows and behind any of the top windows. If the window is not the top window, this flag does not affect the window.
HWND_TOP: place the window at the top of all its windows
HWND_TOPMOST places the window at the top of all other windows and in front of any of the top windows. The window remains at the top even if it is not an active window.

X:
Int, specifies the new X coordinate of the window.

Y:

Int, which specifies the New Y coordinate of the window.

Cx:

Int, specify the new window width

Cy:

Int, specifies the new height of the window.

WFlags:

UINT, indicating the flag of the window status and position. This parameter uses a combination of the following nominal values: SWP_DRAWFRAME draws a box around the window
SWP_FRAMECHANGED sends a WM_NCCALCSIZE message to enter the window, even if the window size does not change. If this parameter is not specified, the message WM_NCCALCSIZE is sent only when the window size changes.
SWP_HIDEWINDOW hide window
SWP_NOACTIVATE does not activate the window
SWP_NOCOPYBITS block the customer Region
SWP_NOMOVE to keep the current position (the X and Y parameters will be ignored)
SWP_NOOWNERZORDER does not change the position and order of all windows
SWP_NOREDRAW window does not automatically redraw
The SWP_NOREPOSITION and SWP_NOOWNERZORDER tags are the same
SWP_NOSENDCHANGING prevents this window from accepting WM_WINDOWPOSCHANGING messages
SWP_NOSIZE to keep the current size (cx and cy will be ignored)
SWP_NOZORDER keep the current position of the window in the list (hWndInsertAfter will be ignored)
SWP_SHOWWINDOW display window
Note:

If the SWP_SHOWWINDOW or SWP_HIDEWINDOW flag is set, the window does not move or change the size. When a window becomes the top-level window, all its subwindows also enter the top-level window. Once it is set to a non-top-level, all its sub-windows will be converted to a non-top-level window.

The reference in the program is as follows:

[DllImport("user32.dll", EntryPoint = "SetWindowPos")]static extern bool SetWindowPos(IntPtr hWnd,IntPtr hWndInsertAfter,int X,int Y,int cx,int cy,uint uFlags);static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);static readonly IntPtr HWND_TOP = new IntPtr(0);const UInt32 SWP_NOSIZE = 0x0001;const UInt32 SWP_NOMOVE = 0x0002;const UInt32 SWP_NOZORDER = 0x0004;const UInt32 SWP_NOREDRAW = 0x0008;const UInt32 SWP_NOACTIVATE = 0x0010;const UInt32 SWP_FRAMECHANGED = 0x0020;const UInt32 SWP_SHOWWINDOW = 0x0040;const UInt32 SWP_HIDEWINDOW = 0x0080;const UInt32 SWP_NOCOPYBITS = 0x0100;const UInt32 SWP_NOOWNERZORDER = 0x0200;const UInt32 SWP_NOSENDCHANGING = 0x0400;const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.