获取控制台程序的HWND和HINSTANCE

来源:互联网 发布:成都和重庆公务员知乎 编辑:程序博客网 时间:2024/05/11 17:24

一,获取HWND的方法:

1,API:HWND GetConsoleWindow(NULL)

Client  Requires Windows Vista, Windows XP, or Windows 2000 Professional. Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server. Header Declared in Wincon.h; include Windows.h. Library Use Kernel32.lib. DLL Requires Kernel32.dll.

 

2, 通过调用 FindWindow() 查找窗口句柄

  来源于:http://support.microsoft.com/kb/124103

因为多个窗口可能具有相同的标题,您应更改当前的控制台窗口标题,以一个唯一的标题。这将有助于防止将返回错误的窗口句柄。若要更改当前的控制台窗口标题中使用 SetConsoleTitle()。下面是此过程:

  1. 调用 GetConsoleTitle() 保存当前控制台窗口标题。
  2. 调用 SetConsoleTitle() 若要更改控制台标题到唯一的标题。
  3. 若要确保窗口标题的调用 Sleep(40) 已更新。
  4. 如果操作失败,调用 FindWindow NULL uniquetitle),以获取该 HWND 此调用将返回 HWND--或 NULL。
  5. 从步骤 1,要还原原始的窗口标题检索调用 SetConsoleTitle() 具有值。

您应该测试结果的 HWND。例如对于您可以测试以查看是否返回的 HWND 与当前进程在 HWND 上调用 GetWindowText() 并将结果与 GetConsoleTitle() 进行比较。
生成的 HWND 是不能保证是适用于所有的窗口句柄操作。

示例代码

下面的函数检索当前控制台应用程序窗口句柄 (HWND)。如果此函数成功,返回值是控制台窗口的句柄。如果将失败函数返回值为 NULL。

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);}

二,获取HINSTANCE的方法

1,SDK API中使用HMODULE GetModuleHandle(NULL);

2,MFC中使用HINSTANCE AfxGetInstanceHandle();

在Win32下 是这样定义这两种返回值的

 
HINSTANCE typedef  HANDLE  HINSTANCE; HMODULE typedef  HINSTANCE HMODULE;
原创粉丝点击