简体   繁体   中英

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); 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~

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 << ")";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM