Rachel Rachel - 1 year ago 67
C++ Question

How to print sentence in the position of the mouse cursor in VC++ Win32 application?

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 <conio.h>
#include <stdio.h>
using namespace std;

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

int main(){
while (1){
POINT cursorPos;
gotoxy(cursorPos.x, cursorPos.y);
cout << cursorPos.x << " " << cursorPos.y;

Thank U~

Answer Source

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. Further adjust the position for x/y offset due to title bar height. Map the coordinates to CONSOLE_SCREEN_BUFFER_INFO::srWindow

COORD getxy()
    POINT pt; 
    HWND hwnd = GetConsoleWindow();

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

    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    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)
        COORD coord = getxy();
        SetConsoleCursorPosition(hout, coord);
        cout << "(" << coord.X << "," << coord.Y << ")";