How do I find the coordinates of the cursor in a console window?

11,252

As per the documentation for the SetConsoleCursorPosition function:

To determine the current position of the cursor, use the GetConsoleScreenBufferInfo function.

In general, if you know how to get or set something, the MSDN documentation for that function will hint at how to do the opposite. That is certainly true in this case.

If we look up the GetConsoleScreenBufferInfo function, we see that we've struck paydirt. It fills in a CONSOLE_SCREEN_BUFFER_INFO structure that, among other things, contains a COORD structure that indicates the current column and row coordinates of the cursor.

There is even an example. Package it up into a function if you want to make it convenient:

COORD GetConsoleCursorPosition(HANDLE hConsoleOutput)
{
    CONSOLE_SCREEN_BUFFER_INFO cbsi;
    if (GetConsoleScreenBufferInfo(hConsoleOutput, &cbsi))
    {
        return cbsi.dwCursorPosition;
    }
    else
    {
        // The function failed. Call GetLastError() for details.
        COORD invalid = { 0, 0 };
        return invalid;
    }
}

As Michael mentioned already in a comment, GetCursorPos doesn't work because it is for the mouse cursor (the arrow), not the cursor (insertion point) in a console window. It is returning valid values, just not the values you are looking for. Lucky that the return types are different, otherwise they'd be easy to mix up. Calling it the "cursor" for a console window is sort of misleading, it probably should be called the caret.

Share:
11,252
user3488862
Author by

user3488862

Updated on June 13, 2022

Comments

  • user3488862
    user3488862 almost 2 years

    I gave the cursor some coordinates using the following code:

    COORD c = { 7, 7 };
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(h, c); 
    

    Now I'm writing some text on the screen, and I want to know the current location of the cursor.

    The only function I found was using POINT and not COORD. So I wrote:

    VOID KeyEventProc(KEY_EVENT_RECORD ker)
    {
        POINT position;
        GetCursorPos(&position);
    
            if (position.y<14 && position.x<9){
                if (ker.bKeyDown)
                    printf("%c", ker.uChar);
            }
    
    }
    

    But the POINT doesn't give the same values as I need. How can I convert it? Or what is the function for getting the current COORD?