获得cmd窗口句柄
来源:百度知道 编辑:UC知道 时间:2024/06/21 08:34:25
HWND WND = FindWindowA (NULL,"C:\WINDOWS\system32\cmd.exe"); 不成功!
HWND WND = FindWindowA (ConsoleWindowClass,"C:\WINDOWS\system32\cmd.exe"); 也不成功;
主要原因有一个是在运行我的程序时也会弹出一个新的控制台程序。
万分感谢!
1.调用 GetConsoleTitle() 来保存当前的控制台窗口标题。
2.调用 SetConsoleTitle() 来将控制台标题更改为一个唯一的标题。
3.调用 Sleep(40),以确保已更新窗口标题。
4.调用 FindWindow(NULL, uniquetitle),以获取 HWND,此调用将返回 HWND, 如果操作失败,将返回 NULL。
5.从步骤 1 中,若要恢复原始窗口标题检索调用 SetConsoleTitle() 的值。
应该测试结果的 HWND。例如可以测试是否返回的 HWND 对应于当前进程在 HWND 上调用 GetWindowText() 并将结果与 GetConsoleTitle() 进行比较。
示例代码
下面的函数中检索当前控制台应用程序窗口句柄 (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" NewWindowTitl