Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor Position c++ GetCursorPos method

In the following code, I want the position of the mouse cursor on the screen, but wherever I move the cursor, I get the same output from the second starred or bolded(not sure) part below(wherever the cursor is): -1957298293 343277548. If anyone has a better method of getting the cursor position or a fix for my code, please help. (Just by the way, the "HANDLE csbiHandle; CONSOLE_SCREEN_BUFFER_INFO csbi;" aren't necessary. They were used in my previous method which also failed)

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <cstdio>
#include <stdio.h>

#ifndef MOUSE_HWHEELED
#define MOUSE_HWHEELED 0x0008
#endif
using namespace std;

int main()
{
LPPOINT point;
HANDLE csbiHandle;
CONSOLE_SCREEN_BUFFER_INFO csbi;
int counter = 0;
DWORD cNumRead, i,fdwMode, fdwSaveOldMode;
INPUT_RECORD irInputBuffer[128];
HANDLE stdHandle;
stdHandle = GetStdHandle(STD_INPUT_HANDLE);
MOUSE_EVENT_RECORD mer;


cout << "|-------------|" << endl
     << "|      A      |" << endl
     << "|-------------|" << endl;
while(counter++<1000)
{
buttonpress:
ReadConsoleInput(stdHandle, irInputBuffer,128, &cNumRead);
**GetCursorPos(point);**
for(i=0; i<cNumRead; i++)
{
    switch(irInputBuffer[i].EventType)
    {
        case MOUSE_EVENT:
        {
            mer = irInputBuffer[i].Event.MouseEvent;

            if(mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
            {
                cout << "left button press" << endl;
                **cout << point->x << " " << point->y << endl;**
            }
            else
            {
                goto buttonpress;
            }
            break;
       }
        default:{
            printf("unknown\n");
            break;}
    }
}
}


return 0;
}
like image 939
someguy Avatar asked Dec 21 '22 12:12

someguy


1 Answers

You can be lucky that your program didn't crash right away. The GetCursorPos function gets an LPPOINT as parameter, but that doesn't mean you should declare a variable of that type. Instead, you should do this:

POINT point;
if (GetCursorPos(&point)) {
  cout << point.x << "," << point.y << "\n";
}

The reason is that your LPPOINT, at the time of the call, is a pointer that points "somewhere", and nobody can say where it points. So it could very well be that it points to read-only memory, and Windows is so nice to check this and don't write to that memory, but instead returns FALSE. You didn't check the return value of the function call, so you cannot know whether it was successful or not.

like image 77
Roland Illig Avatar answered Jan 08 '23 02:01

Roland Illig