Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing mouse/keyboard events outside of form (app running in background)

I have an app that runs in the background (minimized/task tray). I need to be able to detect mouse activity (clicks, move) as well as keyboard activity.

What is the best way to do this given the constraint that my window is not "focused" ?

like image 706
Andy Hin Avatar asked Jul 22 '10 19:07

Andy Hin


2 Answers

Take a look at this library globalmousekeyhook. It is 100% managed c# code to install global mouse and keyboard hooks. It wraps low level hooks into common windows forms keyboard and mouse events.

like image 92
George Mamaladze Avatar answered Oct 23 '22 14:10

George Mamaladze


The magic words are windows hooks. These are created with a p/invoke call to SetWindowsHookEx. You can set up a hook to monitor, among others, keyboard and mouse events. Normally, such hooks are local to the application, but you can also create global hooks. The Microsoft KB shows how.

However, be aware that not all types of global hooks can be used from .NET. In particular, there are only two that you can use: the low-level keyboard and mouse hooks, known as WH_KEYBOARD_LL and WH_MOUSE_LL. Luckily, these are just what you need.

like image 12
Thomas Avatar answered Oct 23 '22 15:10

Thomas