一个例子(以为我从.net framework 1.1开始就没有更新代码)在按下任何键时都有一个事件:
public class Hook
{
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
public static extern int GetCurrentThreadId();
public static event Action Event = null;
private const int WH_KEYBOARD = 2;
private delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
static int _hookKeyboard = 0;
private static HookProc _hookKeyboardProc;
public static bool Install()
{
_hookKeyboardProc = new HookProc(KeyboardHook);
_hookKeyboard = SetWindowsHookEx(WH_KEYBOARD, _hookKeyboardProc, IntPtr.Zero, GetCurrentThreadId());
return _hookKeyboard != 0;
}
public static bool Uninstall()
{
// uninstall keyboard hook
if(!UnhookWindowsHookEx(_hookKeyboard))
return false;
_hookMouseProc = null;
return true;
}
private static int KeyboardHook(int nCode, IntPtr wParam, IntPtr lParam)
{
// if any message - fire event
if(nCode >= 0 && Event != null)
Event();
return CallNextHookEx(_hookKeyboard, nCode, wParam, lParam);
}
}