DEV Community

Cover image for Quick Guide to Mouse Clicking in C#

Posted on

Quick Guide to Mouse Clicking in C#

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:

  1. Add using System.Runtime.InteropServices; to your *.cs file
  2. Add two methods from user32.dll that we will be using:

    public static extern bool SetCursorPos(int X, int Y);
    public static extern void mouse_event(int dwFlags, int dx, int 
    dy, int cButtons, int dwExtraInfo);
  3. mouse_event(?) is method responsible for clicking, while SetCursorPos (?) sets mouse cursor where we want on the screen

  4. 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;
  5. Now we make a click at screen position x=128 and y=256

    mouse_event(LMBDown, 128, 256, 0, 0);
    mouse_event(LMBUp, 128, 256, 0, 0);

and thats it!
Working example:

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
    public static extern bool GetCursorPos(out CursorPos lpPoint);
    public struct CursorPos { public int X; public int Y; }
    static void Main(string[] args)
        CursorPos position;

            if (GetCursorPos(out position))
        } while (!Console.KeyAvailable);
Enter fullscreen mode Exit fullscreen mode


Top comments (0)