How to detect mouse clicks?

You need to write a mouse hook if you want to intercept any mouse clicks, movement, mouse wheel clicks…etc.

This is the only way AFAIK if you want to track mouse activity outside of your own application. You need to import the SetWindowsHookEx(…) function from the User32.dll file if you want to install a hook. It involves interop (PInvoke) and you’ll have to import (DllImport) some functions.

Here’s an official document by Microsoft on how to achieve this in C#:

How to set a Windows hook in Visual C# .NET

I’ll summarize it here, just to be complete the answer should the link die one day.

Starting with the SetWindowsHookEx function:

[DllImport("user32.dll",CharSet=CharSet.Auto,
 CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, 
IntPtr hInstance, int threadId);

Now you can setup your hook. For example:

public class Form1
{
    static int hHook = 0;
    public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
    HookProc MouseHookProcedure;

    private void ActivateMouseHook_Click(object sender, System.EventArgs e)
    {
        if(hHook == 0)
        {
            MouseHookProcedure = new HookProc(Form1.MouseHookProc);
            hHook = SetWindowsHookEx(WH_MOUSE, 
                             MouseHookProcedure,
                             (IntPtr) 0,
                             AppDomain.GetCurrentThreadId());
        }
    }
}

Don’t forget to unhook it afterwards. You’ll need another DllImport for this:

[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

private void DeactivateMouseHook_Click(object sender, System.EventArgs e)
{
    bool ret = UnhookWindowsHookEx(hHook);
}    

You can use the HookProc delegate (MouseHookProcedure) to capture the mouse activity. This involves some marshalling in order to capture the data.

[StructLayout(LayoutKind.Sequential)]
public class POINT 
{
    public int x;
    public int y;
}

[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct 
{
    public POINT pt;
    public int hwnd;
    public int wHitTestCode;
    public int dwExtraInfo;
}

public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{          
    MouseHookStruct MyMouseHookStruct = (MouseHookStruct)
        Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    // You can get the coördinates using the MyMouseHookStruct.
    // ...       
    return CallNextHookEx(hHook, nCode, wParam, lParam); 
}

Don’t forget to call the next item in the hook chain afterwards (CallNextHookEx)!

[DllImport("user32.dll",CharSet=CharSet.Auto,      
 CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, 
IntPtr wParam, IntPtr lParam);

PS: You can do the same for the keyboard.

Leave a Comment