How do I get the console handle of an external application?
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?
A console process uses handles to access the input and screen buffers of its console. A process can use the GetStdHandle, CreateFile, or CreateConsoleScreenBuffer function to open one of these handles.
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() .
A handle is a unique identifier for an object managed by Windows. It's like a pointer, but not a pointer in the sence that it's not an address that could be dereferenced by user code to gain access to some data.
Defines the coordinates of a character cell in a console screen buffer. The origin of the coordinate system (0,0) is at the top, left cell of the buffer.
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.
Remember to cleanup, freeing your handle to the console by calling FreeConsole.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With