theCNG27
theCNG27

Reputation: 425

Problems with GetCursorPos

I'm having problems with GetCursorPos. I use directx to draw a square where the cursor is but my code doesn't work and I have no idea why...

LPPOINT cursorPos = 0;
GetCursorPos(cursorPos);
square->setPosition(D3DXVECTOR2(40.0f,60.0f));  // as a test: works fine...
square->setPosition(D3DXVECTOR2(cursorPos->x, cursorPos->y)); // -> crash

I also tried this:

LPPOINT cursorPos = 0;
GetCursorPos(cursorPos);
float posX = cursorPos->x;  // no crash...
float posY = cursorPos->y;  // no crash...
std::cout << posX << posY <<std::endl; // CRASH!

What am I doing wrong??

Upvotes: 0

Views: 2095

Answers (1)

templatetypedef
templatetypedef

Reputation: 372982

When you declare an LPPOINT, you're declaring a pointer to a POINT object. Therefore, when you write

LPPOINT cursorPos = 0;

You're creating a pointer called cursorPos and setting it to NULL. The call

GetCursorPos(cursorPos);

then fails, because GetCursorPos expects you to provide a pointer to the POINT that you want to fill in with the information and you've provided a NULL pointer. Consequently, when you write

square->setPosition(D3DXVECTOR2(cursorPos->x, cursorPos->y)); // -> crash

You're reading a NULL pointer when trying to read x and y. This leads to undefined behavior, which here is a crash. In the other case, you're also getting undefined behavior, and it just happens to not crash.

To fix this, try declaring an actual POINT object, like this:

POINT cursorPos;

then calling

GetCursorPos(&cursorPos);

then reading the position as

square->setPosition(D3DXVECTOR2(cursorPos.x, cursorPos.y));

Hope this helps!

Upvotes: 7

Related Questions