C # + API to activate a specified form

Source: Internet
Author: User

I am not familiar with the API, which wastes a long time to implement a simple function. Next I will summarize the related items I have checked:

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 the EnumWindows API to enumerate the window. // </summary> class Program {
// Define the global variable of the handle
Public int HANDLE; // defines the delegate public delegate bool CALLBACK (int hwnd, int lparm) of the CALLBACK function; // gets the frontend window HANDLE, set the current window handle [DllImport ("user32.dll")] public static extern int EnumWindows (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); EnumWindo Ws (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 );

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

Some forms, such as NotePad forms and PPT, have different titles, so it is more convenient to search by window type. 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, "Word Mobile"); // determine whether the form is valid if (ParenthWnd! = IntPtr. Zero) {MessageBox. Show ("find window");} else MessageBox. Show ("no window found ");

 

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 find1_wex (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 close the 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; // leftmost Coordinate
Public int Top; // Top coordinate
Public int Right; // rightmost Coordinate
Public int Bottom; // The lowest coordinate.
}

Example:

InPtr awin = GetForegroundWindow (); // get 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; // window height
Int x = rc. Left;
Int y = rc. Top;

(7) Common Operations:

GetClassName (
HWnd: HWND; {specify the window handle}
LpClassName: PChar; {buffer}
NMaxCount: Integer {buffer size}
): Integer; {returned class name size; failed return 0} Get the Class Name of the specified window

GetNextWindow (
HWnd: HWND; {the specified window handle}
UCmd: UINT {specified link options}
): HWND; {0 is returned for failure; 0 is returned for success}
// Optional uCmd values:
GW_HWNDNEXT = 2; {below the same level Z order}
GW_HWNDPREV = 3; {above the Z order of the same level} Get the handle of the window on the Z or Z of the specified window

GetTopWindow (
HWnd: HWND; {the specified window handle}
): HWND; {0 is returned for failure; 0 is returned for success. Top-level sub-window handle} is returned. Obtain the top-level window handle in the sub-window of the specified window.

GetWindow (
HWnd: HWND; {the specified window handle}
UCmd: UINT {specified link options}
): HWND; {0 is returned for failure; 0 is returned for success}

// Optional uCmd values:
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; {one at the same level}
GW_OWNER = 4; {Main Window}
GW_CHILD = 5; {subwindow}: Obtain the handle of the window with a specified relationship with the specified window.

GetWindowTextLength (
HWnd: HWND {window handle}
): Integer; {return window title length} get the window title Length

SetWindowText (
HWnd: HWND; {window handle}
LpString: PChar {New title string pointer}
): BOOL; set the window title

GetDesktopWindow: HWND; {No parameter; return the handle of the desktop window}

(8) There is still a problem to be resolved.

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. The solution will be provided later. Go to dinner first ......

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.