Obtain the handle (hwnd) of the console window and the output return key in the program

Source: Internet
Author: User

1. Get window handle based on class name or window name: http://support.microsoft.com/kb/124103/zh-cn

Win32 API provides no direct method to obtain the window handle associated with a console application. However, you can obtain the window handle by calling findwindow. This function retrieves the window handle based on the class name or window name.


Call to determine the current console title getconsoletitle (). Then provide the title of the current console to findwindow ().

Because multiple windows may have the same title, you should change the title of the current Console window to a unique title. This will help prevent returning the wrong window handle. To change the title of the current Console window, use
Setconsoletitle (). The process is as follows:

  1. Call getconsoletitle () to save the title of the current Console window.
  2. Call setconsoletitle () to change the console title to a unique title.
  3. Make sure that the call sleep (40) for the window title has been updated.
  4. If the operation fails, call findwindow null uniquetitle) to obtain the hwnd. This call will return hwnd -- or null.
  5. From step 1, to restore the original window title search call setconsoletitle () has a value.

You should test the hwnd of the result. For example, you can test to check whether the returned hwnd and the current process call getwindowtext () on hwnd and compare the result with getconsoletitle.

The generated hwnd is not guaranteed to be applicable to all window handle operations.

Sample Code

The following function retrieves the application window handle (hwnd) of the current console ). If this function succeeds, the return value is the handle of the console window. If the return value of the failed function is null. Some error checks are omitted for conciseness.

   HWND GetConsoleHwnd(void)   {       #define MY_BUFSIZE 1024 // Buffer size for console window titles.       HWND hwndFound;         // This is what is returned to the caller.       char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated                                           // WindowTitle.       char pszOldWindowTitle[MY_BUFSIZE]; // Contains original                                           // WindowTitle.       // Fetch current window title.       GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);       // Format a "unique" NewWindowTitle.       wsprintf(pszNewWindowTitle,"%d/%d",                   GetTickCount(),                   GetCurrentProcessId());       // Change current window title.       SetConsoleTitle(pszNewWindowTitle);       // Ensure window title has been updated.       Sleep(40);       // Look for NewWindowTitle.       hwndFound=FindWindow(NULL, pszNewWindowTitle);       // Restore original window title.       SetConsoleTitle(pszOldWindowTitle);       return(hwndFound);   }


2. Use the getconsolewindow function: http://hi.baidu.com/console_app/blog/item/196387028b1893e409fa9330.html

Author: defanive
Blog: console. Dec. CN (Hi. Baidu. com/lele_app)

Windows, all have their unique handles (hwnd ). You can get the window handle to do many things. For console programs, if you can post on the window effect, this third-party tool will be very successful.

Common methods provided on the Internet:

Hwnd hW = findwindow ("lelewindowclass", null );

This is a good method, but it is not highly risky to start from the class aspect.

The API function findwindow has two parameters: Class Name and window title. If the window title is not provided, the returned handle is the window handle with the highest Z-order in the same type of window. Although the execution is only for an instant, we recommend that you provide the title window to be more secure.

Char strtitle [255];
Getconsoletitle (strtitle, 255 );
Hwnd hW = findwindow ("consolewindowclass", strtitle );

Of course, if you want to keep improving, there are more safe ways to use some unpublished APIs in kernel32.dll. After exporting the console-related APIs in kernel32.dll using exclusive, an API named getconsolewindow is found. After searching for references, provide the following code to dynamically load this API and obtain the window handle.

First, global declaration is required:

Typedef hwnd (winapi * procgetconsolewindow )();
Procgetconsolewindow getconsolewindow;

Then enter the following content at the beginning of the main () function:

Hmodule hkernel32 = getmodulehandle ("Kernel32 ");
Getconsolewindow = (procgetconsolewindow) getprocaddress (hkernel32, "getconsolewindow ");

Completed the task of dynamically loading the API function getconsolewindow. The following can be used:

Hwnd cmd = getconsolewindow ();

In my opinion, using the API function getconsolewindow is the safest and best method. In larger console programming, you may need to use the attachconsole to change the host console of the program at any time. In this case, it is not enough to use the first two methods. Although the loaded code is long, it is more universal.

3. Use a program in the console to output the Enter key

(1 ):

Input key [1] = {0 };
Key [0]. type = input_keyboard;
Key [0]. Ki. wvk = vk_return;
Key [0]. Ki. dwflags = 0;
Key [0]. Ki. Time = 0;
Key [0]. Ki. wscan = 0; // vk_return;
Key [0]. Ki. dwextrainfo = 0;
Sendinput (1, key, sizeof (key ));

(2 ):

Keybd_event (0xd, 0, 0 );

(3 ):

After obtaining the console handle (hwnd), you can use this handle to send an ascll message with the Enter key to the console.

Sendmessage (hwndfound, wm_char, 0x0d, 0 );

Method (1) (2) may affect other applications, and method (3) verification does not affect other applications.

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.