Obtaining a Console Window Handle (HWND)Last reviewed: September 29, 1995Article ID: Q124103 |
The information in this article applies to:
SUMMARYIt may be useful to manipulate a window associated with a console application. The Win32 API provides no direct method for obtaining the window handle associated with a console application. However, you can obtain the window handle by calling FindWindow(). This function retrieves a window handle based on a class name or window name. Call GetConsoleTitle() to determine the current console title. Then supply the current console title to FindWindow().
MORE INFORMATIONBecause multiple windows may have the same title, you should change the current console window title to a unique title. This will help prevent the wrong window handle from being returned. Use SetConsoleTitle() to change the current console window title. Here is the process:
The resulting HWND is not guaranteed to be suitable for all window handle operations.
Sample CodeThe following function retrieves the current console application window handle (HWND). If the function succeeds, the return value is the handle of the console window. If the function fails, the return value is NULL. Some error checking is omitted, for brevity. 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);}
|
Additional reference words: 3.10 3.50 4.00 95
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |