钩子示例
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Reflection; using System.IO; using System.Windows.Forms; namespace WindowsApplication1 { public delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam); public enum HookType //枚举,钩子的类型 WindowsMessageHook { MsgFilter = -1, JournalRecord = 0, JournalPlayback = 1, Keyboard = 2, GetMessage = 3, CallWndProc = 4, CBT = 5, SysMsgFilter = 6, Mouse = 7, Hardware = 8, Debug = 9, Shell = 10, ForegroundIdle = 11, CallWndProcRet = 12, KeyboardLL = 13, MouseLL = 14 } [StructLayout(LayoutKind.Sequential)] public class KeyboardHookStruct { public int vkCode; //表示一个在1到254间的虚似键盘码 public int scanCode; //表示硬件扫描码 public int flags; public int time; public int dwExtraInfo; } public class KeyboardHook { private const int WM_KEYDOWN = 0x100; private const int WM_KEYUP = 0x101; private IntPtr nextHookPtr; //记录Hook编号 private HookProc hookProc; [DllImport("User32.dll")] public static extern void UnhookWindowsHookEx(IntPtr handle); [DllImport("User32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); [DllImport("User32.dll")] public static extern IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam); public KeyboardHook() { nextHookPtr = IntPtr.Zero; } public void SetKeyboardHook() { if (nextHookPtr != IntPtr.Zero) return; hookProc = new HookProc(KeyboardhookProc); //键盘事件消息处理函数 nextHookPtr = SetWindowsHookEx((int)HookType.KeyboardLL, hookProc, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); } public void UnKeyboardHook() { if (nextHookPtr != IntPtr.Zero) { UnhookWindowsHookEx(nextHookPtr); //从Hook链中取消 nextHookPtr = IntPtr.Zero; } } private IntPtr KeyboardhookProc(int code, IntPtr wparam, IntPtr lparam) { if (code >= 0) { KeyboardHookStruct myKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lparam, typeof(KeyboardHookStruct)); switch (wparam.ToInt32()) { case WM_KEYDOWN: Console.Write(string.Format("{0}", Convert.ToChar(myKeyboardHookStruct.vkCode))); break; case WM_KEYUP: //Console.WriteLine(string.Format("WM_KEYUP:{0:0}", Convert.ToChar(myKeyboardHookStruct.vkCode))); break; default: break; } } return CallNextHookEx(nextHookPtr, code, wparam, lparam); //返回,让后面的程序处理该消息 } } }