System-wide hooks in the .NET Framework — can it be done?
Yes and no.
Recently I found the need to make a global mouse hook. This is no big deal down at the Win32 API level, where you would just write a dynamic library and then use the SetWindowsHookEx API function. But how to solve this in a managed environment, I thought to myself. The way Windows works doesn’t make this easy.
After searching around a bit I found this at Microsoft’s site:
Global hooks are not supported in the .NET Framework
Except for the WH_KEYBOARD_LL low-level hook and the WH_MOUSE_LL low-level hook, you cannot implement global hooks in the Microsoft .NET Framework. To install a global hook, a hook must have a native DLL export to inject itself in another process that requires a valid, consistent function to call into. This behavior requires a DLL export. The .NET Framework does not support DLL exports. Managed code has no concept of a consistent value for a function pointer because these function pointers are proxies that are built dynamically.Low-level hook procedures are called on the thread that installed the hook. Low-level hooks do not require that the hook procedure be implemented in a DLL.
Makes sense, I thought. So how can we get this working?
After yet more searching I found this article:
Global System Hooks in .NET. It explains how to create an unmanaged C++ DLL and use it from C#!
An interesting possibility would indeed be to have a managed hook (I’ve seen many bad hooks througout the years).
