Lets design a robot program which can simulate mouse and keyboard events on your desktop. Simulator which can automate the keyboard and mouse functions for you, can do almost all possible tasks on your desktop which ranges from setting up a task in the Task Scheduler to booking a movie ticket for you. You can smartly use and customize this piece of code to perform hectic tasks which you have to perform repeatedly like checking email.
|Subscribe us for our YouTube channel and any kind of help|
We shall start with basics of how to simulate keyboard and mouse using c sharp, .NET.
Creating Mouse Events
1. Importing user32.dll from Win32 API
public static extern int SetCursorPos(int x, int y);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_MOVE = 0x0001; /* mouse move */
private const int MOUSEEVENTF_LEFTDOWN = 0x0002; /* left button down */
private const int MOUSEEVENTF_LEFTUP = 0x0004; /* left button up */
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; /* right button down */
declare the function and other members of the user32.dll we are going to use.
2. Setting the mouse position on the screen
This function lets the virtual pointer to come at the specified co-ordinates (X,Y). You can also find the current pointer location using System.Windows.Forms.Control.MousePosition attribute.
3. Performing the mouse click event
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
The above two steps performs mouse down and mouse up function which eventually performs a single click of the mouse.
Creating KeyBoard Events
To perform a Keyboard event, we will use a pre-made dll avaliable to us which makes the code more compact and easy. Click Here to download the InputSimulator.dll...........
Example to write something automatically:
Example to simulate a Key Down:
Simiarly you can explore many other methods exposed by InputSimulator.dll like:
* SimulateModifiedKeyStroke // for Special Keys or a combination of keys
Adding Shortcuts to the Buttons on your GUI
See the below example in which we will over-ride the ProcessCmdKey method of System.Windows.Form. It will make your GUI more easy to operate
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
if (keyData == (Keys.F1))
if (keyData == (Keys.F2))
if (keyData == (Keys.F3))
return base.ProcessCmdKey(ref msg, keyData);