using System;
using System.Runtime.InteropServices; //调用外部dll的命名空间
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
class Test
{
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
const int WH_KEYBOARD_LL = 13;
static IntPtr hook;
static void Main()
{
// Warning - this means trouble!
hook = SetWindowsHookEx( WH_KEYBOARD_LL, new HookProc(MyLLKbdProc),
Marshal.GetHINSTANCE( typeof(Test).Module ), 0 );
// GC.Collect();
System.Windows.Forms.MessageBox.Show( "Press OK to cancel hook and exit." );
UnhookWindowsHookEx( hook );
}
static IntPtr MyLLKbdProc(int nCode, IntPtr wParam, IntPtr lParam)
{
Console.WriteLine( "message: {0}, vk: {1}", (int)wParam, Marshal.ReadInt32( lParam ) );
return CallNextHookEx( hook, nCode, wParam, lParam );
}
}