问题描述
如何获得外部应用程序的控制台句柄?
我有一个程序作为控制台.我有一个第二个程序,可以调用getConsolescreenbufferinfo,但是为此,我需要第一个程序的控制台手柄.给定第一个程序的HWND,我可以得到其控制台的操作吗?
推荐答案
如果您只有hwnd,请致电 getWindowThreadProcessid 从给定的HWND获得PID.之后,请致电 tacterconsole 在给定过程的控制台的过程中,然后致电 getStdhandle 获取一个手柄,以确认您新附加的控制台.现在,您可以致电 getConsolescreenbufferinfo 使用该句柄.
记住要清理,通过调用Freeconsole将手柄释放到控制台.
编辑:这是一些C ++代码,该帖子
#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 } }