How do I get the mouse position (x and y) on the console? C++

Asked

Viewed 1,532 times

3

I have the following code:

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

using namespace std;

int main()
{
    HWND myconsole = GetConsoleWindow();
    HDC mydc = GetDC(myconsole);

    int x = 150;
    int y = 150;

    COLORREF COLOR = RGB(255, 255, 255);

    SetPixel(mydc, x, y, COLOR);

    ReleaseDC(myconsole, mydc);
    cin.ignore();
    return 0;
}

Where a pixel is drawn at the console’s (150, 150) coordinate.

I would like to know how I do to take the coordinate of the mouse position, to use it to draw such pixel.

1 answer

5


I assume your code is windows specific (windows.h).

In Windows environments you can use the function GetCursorPos to get the cursor position relative to the screen.

To translate the coordinates so as to get positions relative to the window you can use the function ScreenToClient.

POINT pt;
GetCursorPos(&pt);
ScreenToClient(HWND, &pt);
// pt.x e pt.y guardam as coordenadas 

Reference: Soen- Get Current cursor position

Browser other questions tagged

You are not signed in. Login or sign up in order to post.