Get console handle

后端 未结 1 1117
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 18:26

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 fo

相关标签:
1条回答
  • 2021-02-04 19:12

    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   
        }   
    }
    
    0 讨论(0)
提交回复
热议问题