Clicking the mouse
Clicking mouse in Windows is done using "Windows API". We will require some methods from Microsoft Windows user32.dll
. Also we need to remember that click is a two stage process: first you click the mouse button down, which generate one event, followed by releasing button (second event). Having said that, here's the steps:
- Add
using System.Runtime.InteropServices;
to your*.cs
file -
Add two methods from
user32.dll
that we will be using:
[DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
mouse_event
(?) is method responsible for clicking, whileSetCursorPos
(?) sets mouse cursor where we want on the screen-
We define human readable variables of earlier mentioned two events - LMB_Down and LMB_Up. Its not necessary as we can just provide hex numbers to the
mouse_event
function, as well.
public const int LMBDown = 0x02; public const int LMBUp = 0x04;
-
Now we make a click at screen position x=128 and y=256
SetCursorPos(128,256); mouse_event(LMBDown, 128, 256, 0, 0); mouse_event(LMBUp, 128, 256, 0, 0);
and thats it!
Working example: https://gitlab.com/-/snippets/3602168
Where's my cursor at?
As only few of us have superhuman ability of telling exact x,y position of the cursor, we can use this piece of code (for example running in separate console app) to tell where the cursor is now at. We still have to use "WinAPI" function GetCursorPos
(?) which returns position result using out
parameter modifier (?) to a struct
that we will have to create on our own as well.
Full code of getting the position of the cursor looks like this:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out CursorPos lpPoint);
public struct CursorPos { public int X; public int Y; }
static void Main(string[] args)
{
CursorPos position;
do
{
if (GetCursorPos(out position))
Console.Write($"{position.X},{position.Y}\r");
} while (!Console.KeyAvailable);
}
}
Top comments (0)