tags:

views:

47

answers:

1
+1  Q: 

Get console handle

Hi,

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?

+3  A: 

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   
    }   
}
Jim Brissom
I get a weird error on attachconsole. error #31 - "A device attached to the system is not functioning"
Cornwell
According to msdn, it fails because the process does not exist. But I check the pid and it is correct. they were both created with the same privileges.
Cornwell