Making the application wait for input


I'm writing a win32 console application in windows 8 using visual studios 2013. The application will get the coordinates of my mouse click anywhere on my screen(not just the console window) and then display the coordinates on the console window. The final plan is to store these click locations and then have the program move to those coordinates and click in the same order. I will probably be coming back for help on this little project of mine. Here is what I have so far
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<Windows.h>
#include<Winuser.h >
using namespace std;

int main()
{
	POINT cursorPos;
	if (GetAsyncKeyState(VK_LBUTTON))
		{
			GetCursorPos(&cursorPos);

			float x = cursorPos.x;
			float y = cursorPos.y;
			cout << "The coordinate of the cursor are (" << x << ',' << y << ')' << endl;
		}
	
	system("PAUSE");
}

The problem with this code is that it doesn't wait for the click and goes straight to the end of the program. I tried using an infinite while loop but that gives my like 50 outputs of the exact same coordinate. The infinite loop isn't a viable option because the plan is make this code a separate function and when I call it it will return the location of the click. So my question is how can I make it wait for the click and then once the mouse is clicked it displays the coordinates only once and then goes to the end of the program?
Last edited on
Well, the problem (as you have noticed) is that unless the user clicks the mouse the instant the program reaches line 9, nothing interesting happens.

Sometimes, to catch a message (like a mouse click), one would put the code in question into a loop. This is called polling.
But, you've also done that, and again, as you've noticed, it isn't quite ideal.

The only real solution in this case that I can offer, is a winapi mouse hook, which might be a bit more advanced for you at this point.
I did some research on hooks and yeah that stuff is way too advanced for me at the moment. I don't quite have the time to learn this yet. On the bright side though I got the remainder of my program working. I'm using the SendInput () function to simulate clicks. The only down side is I have had to hard code the click coordinates. Anyways thanks for the help. I have a lot on my plate right now. Maybe I will have time in the summer to learn more about the winapi.
Topic archived. No new replies allowed.