14

how can i detect mouse clicks on Windows ? (XP/Vista/7). for example when my application is running , it will detect if user click on something (not on that application UI but on Windows UI). if yes , execute another process.

I don't know if this is possible , i am hoping someone can give me some guidance.

Thanks!

abatishchev
  • 98,240
  • 88
  • 296
  • 433
ETAN
  • 3,152
  • 6
  • 26
  • 35
  • This requires a low-level mouse hook. Not exactly a good beginner project. Google +setwindowshookex +wh_mouse_ll. It otherwise makes little sense to start a process on arbitrary mouse clicks. Create your own user interface with a Windows Forms or WPF project. – Hans Passant Sep 21 '11 at 08:55
  • This question is too general. You should be looking into UI technologies such as WPF or Winforms – Amittai Shapira Sep 21 '11 at 08:55
  • 1
    @Amittai: I don't think that's what they're looking to do. They don't want mouse events for the current application... – Merlyn Morgan-Graham Sep 21 '11 at 08:58

3 Answers3

21

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.

Christophe Geers
  • 8,564
  • 3
  • 37
  • 53
  • Is this code working today with win10 because `HookProc` is not in `User32.dll` anymore and not recognized anymore, and seams moved to `winuser.dll` https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-hookproc @Christophe Geers – lupaulus Dec 02 '20 at 12:36
  • @lupaulus That's possible, this answer is 9 years old and predates Windows 10 by 4 years. I suggest consulting the Microsoft documentation. – Christophe Geers Dec 03 '20 at 18:30
6

While Christophe Geers solution helps you to capture the mouse event, it does not provide a complete solution to the issue. Edward wanted to know how to get the click event.

To get the click event, use the solution provided by Christophe Geers. And add/edit the following:

enum MouseMessages
{
    WM_LBUTTONDOWN = 0x0201,
    WM_LBUTTONUP = 0x0202,
    WM_MOUSEMOVE = 0x0200,
    WM_MOUSEWHEEL = 0x020A,
    WM_RBUTTONDOWN = 0x0204,
    WM_RBUTTONUP = 0x0205
}

public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    //Marshall the data from the callback.
    MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    if (nCode >= 0 &&
        MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
    {
        // Do something here
    }
    return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}
Pic Mickael
  • 1,244
  • 19
  • 36
6

Windows hooking mechanism is what you need to work with. Take a look at this article: Processing Global Mouse and Keyboard Hooks in C#

Dyppl
  • 12,161
  • 9
  • 47
  • 68