VC++ Win32应用程序如何在鼠标光标位置打印语句?

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

我想在鼠标光标所在的位置打印一些东西,所以我使用POINT cursorPos; GetCursorPos(&cursorPos); 获取鼠标光标的位置。

然后我将控制台光标设置到 位置,并打印鼠标坐标。但是结果不正确。

代码如下:

 #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;
   }
}

谢谢你~

使用GetConsoleScreenBufferInfo to find the cursor position in console window. See this

在控制台程序中跟踪鼠标位置可能没有用。如果您确实需要鼠标指针的位置,则必须将桌面坐标转换为控制台坐标 window。

获取控制台window的句柄GetConsoleWindow() 使用 ScreenToClient 将鼠标指针位置从屏幕转换为客户端。将坐标映射到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 << ")";
    }
}