键盘钩子实现代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Runtime.InteropServices; namespace myHookTest { public partial class frmTest : Form { public frmTest() { InitializeComponent(); } //委托 public delegate int HookProc(int Code, IntPtr wParam, IntPtr lParrm); private static int hHook = 0; public bool isGo = false; public const int WH_KEYBOARD_LL = 13; HookProc KeyBoardHookProcedure;//委托对象的实例 //键盘Hook的结构函数 [StructLayout(LayoutKind.Sequential)] public class KeyBoardHookStruct { public int vkCode; public int scanCode; public int flags; public int time; public int dwExtraInfo; } #region 钩子的api函数 //设置钩子 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); //抽调钩子 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool UnhookWindowsHookEx(int hHook); //调用下一个钩子 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int CallNextHookEx(int idCode, int nCode, IntPtr wParam, IntPtr lParam); #endregion //安装钩子 public void hookStart() { if (hHook == 0) { //实例化委托对象 KeyBoardHookProcedure = new HookProc(keyBoardHookProc); hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); //如果抽取钩子失败 if (hHook == 0) { hookClear(); this.lblStatus.Text = "设置失败"; } } } //清除钩子 public void hookClear() { bool retKeyBoard = true; if (hHook != 0) { retKeyBoard = UnhookWindowsHookEx(hHook); hHook = 0; } if (!retKeyBoard) this.lblStatus.Text = "抽取失败"; } //处理键盘按下的信息 public int keyBoardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { KeyBoardHookStruct kbh = (KeyBoardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct)); if (!isGo) { this.txtKeyBoard.Text += ((char)kbh.vkCode).ToString(); isGo = true; } else { isGo = false; } //if ((int)Control.ModifierKeys==(int)Keys.Control&& kbh.vkCode == (int)Keys.E) //{ // MessageBox.Show(DateTime.Now.ToShortTimeString()); //} if (this.txtKeyBoard.Text.ToLower() == "iloveyou") { MessageBox.Show("Hehe"); } } return CallNextHookEx(hHook, nCode, wParam, lParam); } private void frmTest_Load(object sender, EventArgs e) { } private void btnOpen_Click(object sender, EventArgs e) { hookStart();//开启钩子 } private void btnClose_Click(object sender, EventArgs e) { hookClear();//关闭钩子 } } }
界面图片: