获取控制台手柄 [英] Get console handle
问题描述
我如何得到外部应用程序的控制台处理?
How do I get the console handle of an external application?
我有作为运行控制台程序。我有一个第二个方案,将呼叫GetConsoleScreenBufferInfo,但我需要的第一个程序的控制台句柄。是否有可能给出的第一个程序,我可以得到它的主机手柄的HWND?
I have a program running as a console. I have a 2nd program that will call GetConsoleScreenBufferInfo, but for that I need the console handle of the first program. Is it possible that given the HWND of the 1st program I can get its console handle?
推荐答案
如果你只有一个HWND,通话的 GetWindowThreadProcessId 从给定HWND获得PID。随后,致电 AttachConsole 以附上您的调用进程的特定进程的控制台,然后调用 GetStdHandle 来获取句柄到新连接控制台标准输出。现在,您可以调用 GetConsoleScreenBufferInfo 使用处理的。
If you only have a HWND, call GetWindowThreadProcessId to obtain a PID from a given HWND. Afterwards, call AttachConsole to attach your calling process to the console of the given process, then call GetStdHandle to obtain a handle to STDOUT of your newly attached console. You can now call GetConsoleScreenBufferInfo using that handle.
记住要清理,通过调用FreeConsole释放你的句柄到控制台。
Remember to cleanup, freeing your handle to the console by calling FreeConsole.
修改:下面是一些C ++ code去与该职位
Edit: Here is some C++ code to go with that post
#include <sstream>
#include <windows.h>
// ...
// assuming hwnd contains the HWND to your target window
if (IsWindow(hwnd))
{
DWORD process_id = 0;
GetWindowThreadProcessId(hwnd, &process_id);
if (AttachConsole(process_id))
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdOut != NULL)
{
CONSOLE_SCREEN_BUFFER_INFO console_buffer_info = {0};
if (GetConsoleScreenBufferInfo(hStdOut, &console_buffer_info))
{
std::stringstream cursor_coordinates;
cursor_coordinates << console_buffer_info.dwCursorPosition.X << ", " << console_buffer_info.dwCursorPosition.Y;
MessageBox(HWND_DESKTOP, cursor_coordinates.str().c_str(), "Cursor Coordinates:", MB_OK);
}
}
else
{
// error handling
}
FreeConsole();
}
else
{
// error handling
}
}
这篇关于获取控制台手柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!