9

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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user3488862
  • 1,329
  • 2
  • 12
  • 16
  • 1
    [`GetCursorPos`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms648390(v=vs.85).aspx) is for the mouse cursor. The documentation is quite clear. – Jabberwocky Mar 04 '16 at 15:45
  • You'd have known the answer if you'd read the documentation for `SetConsoleCursorPosition`. Don't call API functions without reading their documentation. – David Heffernan Mar 04 '16 at 16:12

1 Answers1

15

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574