Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get console handle

Tags:

c++

c

winapi

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?

like image 954
Cornwell Avatar asked Oct 04 '10 21:10

Cornwell


People also ask

What is handle console in C++?

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.

How do you get window 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() .

What are handles in Windows?

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.

What is Coord in C++?

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.


1 Answers

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   
    }   
}
like image 54
Jim Brissom Avatar answered Oct 06 '22 11:10

Jim Brissom