-1

I want to print something in the position where the mouse cursor is, so I use POINT cursorPos; GetCursorPos(&cursorPos); to get the position of mouse cursor.

Then I set the console cursor to the position, and print the mouse coordinates. However the result is not correct.

Here's the code:

 #include<iostream>
 #include<Windows.h>
 #include <conio.h>
 #include <stdio.h>
 using namespace std;

 void gotoxy(int column, int line){
     COORD coord;
     coord.X = column;
     coord.Y = line;
     SetConsoleCursorPosition(
         GetStdHandle(STD_OUTPUT_HANDLE),
         coord
     );
 }

int main(){
   while (1){
       POINT cursorPos;
       GetCursorPos(&cursorPos);
       system("pause");
       gotoxy(cursorPos.x, cursorPos.y);
       cout << cursorPos.x << " " << cursorPos.y;
   }
}

Thank U~

Rachel
  • 47
  • 6

1 Answers1

1

Use GetConsoleScreenBufferInfo to find the cursor position in console window. See this example

Tracking mouse position in a console program may not be useful. If you really need the position of mouse pointer, you have to convert from desktop coordinates to to console window coordinates.

Get the console window's handle GetConsoleWindow() Use ScreenToClient to convert mouse pointer position from screen to client. Map the coordinates to CONSOLE_SCREEN_BUFFER_INFO::srWindow

COORD getxy()
{
    POINT pt; 
    GetCursorPos(&pt);
    HWND hwnd = GetConsoleWindow();

    RECT rc;
    GetClientRect(hwnd, &rc);
    ScreenToClient(hwnd, &pt);

    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO inf;
    GetConsoleScreenBufferInfo(hout, &inf);

    COORD coord = { 0, 0 };
    coord.X = MulDiv(pt.x, inf.srWindow.Right, rc.right);
    coord.Y = MulDiv(pt.y, inf.srWindow.Bottom, rc.bottom);
    return coord;
}


int main() 
{
    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    while (1)
    {
        system("pause");
        COORD coord = getxy();
        SetConsoleCursorPosition(hout, coord);
        cout << "(" << coord.X << "," << coord.Y << ")";
    }
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • There's no title bar inside client area. – Ben Voigt Oct 12 '16 at 23:46
  • It works! I write this because I would like to write a PlaneWar and use the mouse to move the plane. I was wondering how to get the coordinate without waiting an input "_getch()". Thanks a lot. – Rachel Oct 13 '16 at 01:58
  • 1
    I recommend a regular windows program for developing games. You need real time message handling for mouse/keyboard, drawing hi-resolution images, this can't be done in console. – Barmak Shemirani Oct 13 '16 at 04:42