c#钩子学习笔记(一)
鼓捣了好大时候终于有一点眉目了,先看看代码吧
Hook类
using System; using System.Runtime.InteropServices; using System.Reflection; using System.Threading; using System.Windows.Forms; namespace TestGouZi { class HookClass {
IntPtr _nextHookPtr; //记录Hook编号 internal enum HookType //枚举,钩子的类型 { 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, }; #region 引入api [DllImport("kernel32.dll")] static extern int GetCurrentThreadId(); //取得当前线程编号的API [DllImport("User32.dll")] internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API [DllImport("User32.dll")] internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); //设置Hook的API [DllImport("User32.dll")] internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam); //取得下一个Hook的API #endregion //声明一个委托 internal delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam); //添加一个钩子处理过程 IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam) { if (code < 0) return CallNextHookEx(_nextHookPtr, code, wparam, lparam); //返回,让后面的程序处理该消息 if (wparam.ToInt32() == 98 || wparam.ToInt32() == 66) //如果用户输入的是 b { MessageBox.Show("a"); //this.textBox1.Text = "a"; return (IntPtr)1; //直接返回了,该消息就处理结束了 } else { return IntPtr.Zero; //返回,让后面的程序处理该消息 } } #region 设置钩子、卸载钩子 public void SetHook() { if (_nextHookPtr != IntPtr.Zero) //已经勾过了 return; HookProc myhookProc = new HookProc(MyHookProc); //声明一个自己的Hook实现函数的委托对象 _nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc, IntPtr.Zero, GetCurrentThreadId()); //加到Hook链中 } public void UnHook() { if (_nextHookPtr != IntPtr.Zero) { UnhookWindowsHookEx(_nextHookPtr); //从Hook链中取消 _nextHookPtr = IntPtr.Zero; } } #endregion } }
调用类
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace TestGouZi { public partial class Form1 : Form { public Form1() { InitializeComponent(); } HookClass hc; private void button1_Click(object sender, EventArgs e) { hc = new HookClass(); hc.SetHook(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { hc.UnHook(); } } }
虽然实现的功能比较简单,但是比较适合像我这样的菜鸟入门,由于看了好多,大部分都感觉都比较复杂不适合入门。
可以参考下http://www.cnblogs.com/bfyx/archive/2012/10/31/2747744.html这个文章里的知识,理解起来会更好一点
作者:冰封一夏
出处:http://www.cnblogs.com/bfyx/
HZHControls官网:http://www.hzhcontrols.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git