简体   繁体   中英

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. 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(). 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;
}

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