简体   繁体   English

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

[英]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); 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.使用GetConsoleScreenBufferInfo在控制台窗口中查找光标位置。 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.获取控制台窗口的句柄GetConsoleWindow()使用ScreenToClient将鼠标指针位置从屏幕转换到客户端。 Map the coordinates to CONSOLE_SCREEN_BUFFER_INFO::srWindow将坐标映射到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 << ")";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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