简体   繁体   English

如何使用 graphics.h 获取光标相对于窗口的位置?

[英]How do I get my cursor's position with respect to the window using graphics.h?

I've just recently learned how to get my mouse position but if I move my window it is having a problem.我最近刚刚学会了如何获取鼠标位置,但是如果我移动窗口,就会出现问题。 Example, I want to draw a dot in the position of the mouse coordinate (x = 100, y = 100) so the system will draw at that coordinate in the window and that's the problem because, the mouse position is read according to the position of the SCREEN instead of the WINDOW.例如,我想在鼠标坐标 (x = 100, y = 100) 的位置绘制一个点,因此系统将在窗口中的该坐标处绘制,这就是问题所在,因为鼠标位置是根据位置读取的的屏幕而不是窗口。 If I can somehow get the mouse coordinate according to the window instead of the screen that would fix the problem.如果我能以某种方式根据窗口而不是屏幕来获取鼠标坐标,则可以解决问题。

照片

#include<graphics.h>
#include<iostream>
#include<windows.h>
using namespace std;

int main()
{
    initwindow(800,600);
    POINT CursorPosition;

    while(1)
    {
        GetCursorPos(&CursorPosition);

        cout << CursorPosition.x << endl;
        cout << CursorPosition.y << endl;

        if(GetAsyncKeyState(VK_LBUTTON)) {
        bar(CursorPosition.x, CursorPosition.y, CursorPosition.x+50, 
        CursorPosition.y+50);
        }

        delay(5);
        Sleep(5);
        system("cls");
    }
}

Here is a simple solution which shows you how to convert cursor position to window position.这是一个简单的解决方案,向您展示如何将光标位置转换为窗口位置。 This Proof of Concept utilizes GetForeGroundWindow(), GetCursorPosition() and ScreenToClient().此概念证明使用 GetForeGroundWindow()、GetCursorPosition() 和 ScreenToClient()。 Hold right mouse button and move your mouse around the console window to see the output按住鼠标右键并在控制台窗口周围移动鼠标以查看输出

#include <iostream>
#include <windows.h>

int main()
{
    while (1)
    {
        if (GetAsyncKeyState(VK_RBUTTON))
        {
            POINT pnt;
            GetCursorPos(&pnt);
            ScreenToClient(GetForegroundWindow(), &pnt);

            std::cout << "x: " << pnt.x << " y: " << pnt.y << std::endl;

            Sleep(300);
        }
    }

    return 0;
}

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

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