Search code examples
c#windowsmouseeventmousedesktop-application

Global mouse down detection


How can I detect when a mouse is down (globablly) on Windows through C#? I'm trying to bind a function to when my, e.g., right button is down.

How it would work:
Right mouse button down -> On event call -> Function called
Right mouse button up -> On event call -> Function called


Solution

  • You can use Windows Hooks from WinApi. An example named "Download source files [Version 2]" from codeproject article https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C contains static class named HookManager.

    When you subscribe to HookManager.MouseClick, you will receive a callback on every mouse click on any window in your system (not just in your app). And Button property of MouseEventArgs e parameter will help you to determine which button is clicked.

    See TestFormStatic class in example project.