Retrieving Mouse Position (X & Y Coords) and Clicking - Using C++

what is current mouse position and how to click at it (simulation) using cpp programing

Why we need mouse location finder?

Let's assume that we are addicted to a game which requires their players to click at specific places after certain time interval OR we have a challenge where players have to click as fast as they can on any spot.

Finding X and Y of Mouse in Cpp Program

Why implement it in C++

In above scenarios, we can use any for the freely available automation tool to accomplice the same task. But what if the clicks are to simulated as per given condition / logical evaluation. I came across this kind for problem once and decided to make a tool in C / C++ which does the same. So, in this post I am sharing the relevant portion of code which could be implemented in any project for figuring out mouse position and simulation click at that coordinate.

Code :

//Program that detects mouse location and stores it.
    //The stored value is used later to move mouse to that place
    //and simulate click
    #include <iostream>
    #include <windows.h>
    #include <stdlib.h>
    #include <limits>
    using namespace std;
    int main()
    {
        int a, b;
        SetConsoleTitle("Mouse Position Finder");
        cout << "Enter Key to scan mouse position:" <<endl;
        cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
        POINT p;
        if (GetCursorPos(&p))
        {
         a = (int)p.x;
         b = (int)p.y;
        }
        cout << "Status:" << endl;
        cout << "X coordinate of mouse: " << a <<endl;
        cout << "Y coordinate of mouse: " << b <<endl;
        cout << "Clicking at above position in 100 ms"<< endl;
        SetCursorPos(a,b);
        Sleep(100);
        mouse_event(MOUSEEVENTF_LEFTDOWN, a, b, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, a, b, 0, 0);
        return 0;
    }
  

Output :

Finding X and Y of Mouse in Cpp Program Output
\0

Post a Comment

© MadCap-ed. All rights reserved.