Simulate mouse clicks

Pages: 12
Hey, a friend of mine sent me an invitation on facebook to this game where you have to click your mouse as many times as possible within 10 seconds. I thought it would be funny to create a program that does that for you and could click for you as you move your mouse, is it possible? Or would you have to use co-ordinates?

Sorry if the title is misleding for this section but as you can see, its not exactly importatnt lol.
It would definitely be difficult, but not impossible. There is something in the winAPI (I've forgotten what) that does just that, but I've never been able to work it. I think in Linux you could to it by writing to /dev/mouse or something but I have no idea.
I created a program like that before, let me see if I can find it again.
Thank you NGen, and thanks Bazzy I will take a look, although this is my first experience with WinAPI!
I can't find it, but I still remember how to do it. Give me about 15-20 minutes, I should have it by then.
Sorry for double posting, but I finished the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <windows.h>

bool KeyIsPressed ( unsigned char k ) {
	USHORT status = GetAsyncKeyState ( k );
	return (( ( status & 0x8000 ) >> 15 ) == 1) || (( status & 1 ) == 1);
}

int WINAPI WinMain ( HINSTANCE hInst, HINSTANCE P, LPSTR CMD, int nShowCmd ) {

	HWND target = GetForegroundWindow ( );
	//	pt is for the mouse position, wrect is for the client information. The mouse coords to be sent to the window
	//		must be relative to the top-left corner of the client area, so I have to include that too.
	POINT pt;
	RECT wrect;

	while ( true ) {

		//	ctrl + T to make the front-most window the targetted window
		if ( KeyIsPressed ( VK_CONTROL ) && KeyIsPressed ( 'T' ) ) {
			target = GetForegroundWindow ( );
		}

		//	ctrl + esc to quit
		if ( KeyIsPressed ( VK_CONTROL ) && KeyIsPressed ( VK_ESCAPE ) ) {
			break;
		}

		//	ctrl + left alt to send messages every 5 milliseconds to the target window
		if ( KeyIsPressed ( VK_CONTROL ) && KeyIsPressed ( VK_LMENU ) ) {
			GetCursorPos ( &pt );
			GetClientRect ( target, &wrect );
			//	Final argument holds the mouse positions
			PostMessage ( target, WM_LBUTTONDOWN, 0, ( pt.x - wrect.left ) & ( ( pt.y - wrect.top ) << 16 ) );
			PostMessage ( target, WM_LBUTTONUP, 0, ( pt.x - wrect.left ) & ( ( pt.y - wrect.top ) << 16 ) );

			Sleep ( 5 );
		}

	}

	return 0;

}


You may have to select the Flash window before you can begin sending the messages, but that should work. It worked on VC++, at least.
Last edited on
Cool. Now I wonder how you would do that on Unix...
I made this cruddy one for mucking around on a few facebook clicking games. 20,000 Clicks ftw.

The click function is commented out.
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#include <windows.h>
#include <iostream>
#include <vector>
#include "Timer.h"

/*
 *	Mouse clicking console application.
 *	Instructions:
 *	1: Set how long you would like the app to run for.
 *	2: Move the mouse to the location you would like it to click at and press control to save that point.
 *	   You can add as many points as you want and this app will alternate through them.
 *	   Push 'c' to stop saving the points and begin the demo.
 *     *** If you don't want to save any points and want control of the mouse yourself - then don't save
 *	       any points and just push 'c' to continue past that screen. ***
 *	3: After the 5 second countdown the application will start clicking at the locations you gave it. Or
 *	   if you set no locations will click at the current location your mouse is at.
 *     *** Push esc during this stage if you wish to stop or exit the program ***
 *
 *  #: ******* REMOVE OR EDIT THE COMMENTS AT LINE 120 TO 126 *******
 */

// Function Declarations
void  LeftClick();														// Left clicks the mouse if called.
POINT GetMousePosition();												// Returns the mouses current position.
void  SetMousePosition(POINT& mp);										// Sets the mouses position.

int main()
{
	// Get the current console window.
	HWND myWindow;
	AllocConsole();
	myWindow = FindWindowA( "ConsoleWindowClass", NULL );
	
	// Variables
	float seconds           = 0.0f;										// Timer for how long the app runs.
	int   clicks            = 0;										// Number of clicks in the amount of time the app runs.
	float waitTime          = 0.0f;										// User input of howlong the app runs.
	bool  running           = true;										// Value to keep our app running.
	bool  getMousePositions = true;										// Value if true lets us make a list of mouse positions.
	int   vectorPosition    = 0;										// Value to keep track of our position in the mousePoints vector.
	int   vectorSize        = 0;										// Size of the mousePoints vector.
	bool  hasPoints         = false;									// Default false if we have no mouse points created.

	std::vector<POINT> mousePoints;										// Vector container for our mouse points.

	std::cout << "=== READ ME ===" << std::endl;
	std::cout << "*** Warning - Make sure you don't have the mouse over something important! ***" << std::endl;
	std::cout << "*** This window will close after a 5 second countdown and start clicking!! ***" << std::endl;
	std::cout << "*** After the wait time you enterd the window will open itself again.      ***" << std::endl;

	std::cout << "\n\nHow long do you want the mouse to click for in seconds \n\n >> ";
	std::cin >> waitTime;
	std::cout << std::endl;

	do
	{
		std::cout << "Press ctrl to add the current mouse position to the list or 'C' to continue" << std::endl;
		POINT mouse = GetMousePosition();
		std::cout << "Mouse X : " << mouse.x << "                " << std::endl;
		std::cout << "Mouse Y : " << mouse.y << "                " << std::endl;
		std::cout << "\nPoints saved in list : " << mousePoints.size() << std::endl;

		// If ctrl is pushed add the mouses location the the mousePoints vector.
		if(GetAsyncKeyState(VK_CONTROL))
		{
			hasPoints = true;
			mousePoints.push_back(mouse);
			std::cout << "Added Point (" << mouse.x << ", " << mouse.y << ")" << std::endl;
			Sleep(250);
		}
		// If 'c' is pushed start the clicking after the 5 second count down.
		if(GetAsyncKeyState('C'))
		{
			getMousePositions = false;
		}

		COORD pos = {0, 10};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);

	}while( getMousePositions );

	// Create a timer class.
	Timer t;
	t.InitGameTime();
	t.GetDeltaTime();
	// Set DT to 5 for now to start the 5 second count down.
	float DT  = 5.0f;

	do
	{
		DT -= t.GetDeltaTime();		
		COORD pos = {0,15};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
		std::cout << "Clicks will start in : " << DT << std::endl;

	}while(DT > 0.0f);

	// Reset DT.
	DT = 0.0f;
	// Hide the console window.
	ShowWindow(myWindow,0);
	// Set the number of elements in our vector to its size minus one.
	vectorSize = (mousePoints.size() - 1);

	do
	{
		DT += t.GetDeltaTime();

		// If we have any points in the mousePoints vector. Alternate through them
		// and set the mouses location to the current point we are looking at in mousePoints.
		if(hasPoints)
		{
			SetMousePosition(mousePoints[vectorPosition]);
			vectorPosition++;
			if(vectorPosition > vectorSize)
			{
				vectorPosition = 0;
			}
		}
		// Remove the comment from the line below to enable the clicking.
		//LeftClick();

		// Somes of the games i've tested this on need a small pause to register all the clicks.
		// Enable this if you have that problem. And/or click the object you want to constantly click first before
		// the 5 second timer runs out.
		Sleep(1);

		clicks++;
		if( DT > 1.0f )
		{
			seconds += DT;
			DT = 0.0f;
		}
		// If escape is presses quit the program.
		if(GetAsyncKeyState(VK_ESCAPE))
		{
			running = false;
		}

	}while(seconds < waitTime && running);

	std::cout << "Finished - Mouse Was Clicked : " << clicks << " times in " << seconds << " seconds" << std::endl;
	ShowWindow(myWindow,1);
}

//
// Desc    : Clicks the left mouse button down and releases it.
// Returns : Nothing.
//
void LeftClick()
{  
	INPUT    Input={0};													// Create our input.

	Input.type        = INPUT_MOUSE;									// Let input know we are using the mouse.
	Input.mi.dwFlags  = MOUSEEVENTF_LEFTDOWN;							// We are setting left mouse button down.
	SendInput( 1, &Input, sizeof(INPUT) );								// Send the input.

	ZeroMemory(&Input,sizeof(INPUT));									// Fills a block of memory with zeros.
	Input.type        = INPUT_MOUSE;									// Let input know we are using the mouse.
	Input.mi.dwFlags  = MOUSEEVENTF_LEFTUP;								// We are setting left mouse button up.
	SendInput( 1, &Input, sizeof(INPUT) );								// Send the input.
}

//
// Desc    : Gets the cursors current position on the screen.
// Returns : The mouses current on screen position.
// Info    : Used a static POINT, as sometimes it would return trash values
//
POINT GetMousePosition()
{
	static POINT m;
	POINT mouse;
	GetCursorPos(&mouse);
	m.x = mouse.x;
	m.y = mouse.y;
	return m;
}

//
// Desc    : Sets the cursors position to the point you enter (POINT& mp).
// Returns : Nothing.
//
void SetMousePosition(POINT& mp)
{
	long fScreenWidth	    = GetSystemMetrics( SM_CXSCREEN ) - 1; 
	long fScreenHeight	    = GetSystemMetrics( SM_CYSCREEN ) - 1; 

	// http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx
	// If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535.
	// The event procedure maps these coordinates onto the display surface.
	// Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.
	float fx		        = mp.x * ( 65535.0f / fScreenWidth  );
	float fy		        = mp.y * ( 65535.0f / fScreenHeight );		  
				
	INPUT Input             = { 0 };			
	Input.type		        = INPUT_MOUSE;

	Input.mi.dwFlags	    = MOUSEEVENTF_MOVE|MOUSEEVENTF_ABSOLUTE;
				
	Input.mi.dx		        = (long)fx;
	Input.mi.dy		        = (long)fy;

	SendInput(1,&Input,sizeof(INPUT));
}
timer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#ifndef _TIMER_H
#define _TIMER_H

#include <windows.h>

class Timer
{
	public:
		// Timer ctor
		Timer();
		// Timer dtor
		~Timer();

		// Init the game time
		void								InitGameTime();
		// Gets the current game time
		float								GetGameTime();
		// Gets the FPS
		float								GetFramesPerSecond();
		// Gets the DT
		float								GetDeltaTime();
			
	private:
		float								timeAtGameStart;
		UINT64								ticksPerSecond;

		float								lastUpdate;
		float								fpsUpdateInterval;
		unsigned int						numFrames;
		float								fps;

		float								lastGameTime;
};

#endif//_TIMER_H 


timer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "Timer.h"

Timer::Timer()
{
	this->lastUpdate        = 0;
	this->fpsUpdateInterval = 1.0f;
	this->numFrames         = 0;
	this->fps               = 0;
	this->lastGameTime      = 0;
	this->timeAtGameStart   = 0;

	this->InitGameTime();
}
Timer::~Timer()
{
}

// Init The Game Timer
void Timer::InitGameTime()
{
	// We need to know how often the clock is updated
	QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);

	//Gets the time at the start of the game
	timeAtGameStart = GetGameTime();
}

// Gets The Game Time
float Timer::GetGameTime()
{
	UINT64 ticks;
	float time;

	QueryPerformanceCounter((LARGE_INTEGER *)&ticks);

	time = (float)(__int64)ticks/(float)(__int64)ticksPerSecond;
	
	time -= timeAtGameStart;
	return time;
}

// Get Frames Per Second
float Timer::GetFramesPerSecond()
{
	numFrames++;
	float currentUpdate = GetGameTime();
	if( currentUpdate - lastUpdate > fpsUpdateInterval )
	{
		fps = numFrames / (currentUpdate - lastUpdate);
		lastUpdate = currentUpdate;
		numFrames = 0;
	}
	return fps;
}

// Get Delta Time
float Timer::GetDeltaTime()
{
	float dt = GetGameTime() - lastGameTime;
	lastGameTime += dt;
	return dt;
}
closed account (S6k9GNh0)
On Linux, you'd have to interact with the Xorg server. I'm grown rather fed up with Xorg so it's probably going to be a bit more difficult than it is in Windows though once again, not impossible. I can actually give you some code to help you get started (or probably finished code) if you want....
If you're talking to me, I don't need it. Personally, I find GUI programming boring and like to stick to console stuff for now.

If you're talking to mcleano, ignore this message.
Mythios you're program did not run under VC++. This may be my fault, i've never compiled a program using more than just the .cpp so I may be doing it wrong.
closed account (S6k9GNh0)
GUI programming is hella boring. But when your sick of using so many commands that could easily be automated through a batch command or better yet, you could make a GUI that did just about everything for you and then some, you grit your teeth and go through with it.


Btw, I'm not talking about GUI programming. When using Linux and you need to interact with a window, your forced to use Xorg's libraries. This includes any input.
Heres the VC 2008 Project if you want it mcleano - http://cplusdev.com/Code/Mouse%20Hacker.zip
You weren't? Oh, ok.

And it's not that I want a GUI to do "everything" for me; it's that users don't tend to like command line apps; so we get forced into writing them. That's my £0.012 anyway.
Haha thats fantastic Mythios! Much obliged!
No problem :)
... cough cough *little buggy* cough ... lol
Hahaha, was a pretty quick build. What do you find buggy though?
Pages: 12