C# 钩子函数

本文介绍了一种使用C#实现键盘钩子的方法,通过创建钩子函数类,利用DllImport导入Windows API函数SetWindowsHookEx、UnhookWindowsHookEx和CallNextHookEx,实现了键盘事件的监听与处理。具体包括键盘钩子的安装与卸载,以及如何在应用程序中使用这些钩子进行特定的键盘事件响应。
摘要由CSDN通过智能技术生成

本章讲述:钩子函数

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    public class KeyboardHook		//钩子函数类  
    {
        #region 属性

        private const int WH_KEYBOARD_LL = 13; //键盘
        //键盘处理事件委托.
        private delegate int HookHandle(int nCode, int wParam, IntPtr lParam);

        //客户端键盘处理事件
        public delegate void ProcessKeyHandle(HookStruct param, out bool handle);

        //接收SetWindowsHookEx返回值
        private static int _hHookValue = 0;

        //勾子程序处理事件
        private HookHandle _KeyBoardHookProcedure;
        //Hook结构
        [StructLayout(LayoutKind.Sequential)]
        public class HookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }

        private IntPtr _hookWindowPtr = IntPtr.Zero;
        #endregion

        #region

        //设置钩子
        [DllImport("user32.dll")]
        private static extern int SetWindowsHookEx(int idHook, HookHandle lpfn, IntPtr hInstance, int threadId);

        //取消钩子
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern bool UnhookWindowsHookEx(int idHook);

        //调用下一个钩子
        [DllImport("user32.dll")]
        private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);

        //获取当前线程ID
        [DllImport("kernel32.dll")]
        private static extern int GetCurrentThreadId();

        //Gets the main module for the associated process.
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetModuleHandle(string name);

        #endregion

        #region 事件
        //构造器
        public KeyboardHook() { }

        //外部调用的键盘处理事件
        private static ProcessKeyHandle _clientMethod = null;

        /// summary
        /// 安装勾子
        /// summary
        /// param name="hookProcess" ;外部调用的键盘处理事件     
        public void InstallHook(ProcessKeyHandle clientMethod)
        {
            _clientMethod = clientMethod;

            // 安装键盘钩子
            if (_hHookValue == 0)
            {
                _KeyBoardHookProcedure = new HookHandle(GetHookProc);

                _hookWindowPtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);

                _hHookValue = SetWindowsHookEx(
                    WH_KEYBOARD_LL,
                    _KeyBoardHookProcedure,
                    _hookWindowPtr,
                    0);

                //如果设置钩子失败.
                if (_hHookValue == 0)

                    UninstallHook();
            }
        }

        //取消钩子事件
        public void UninstallHook()
        {
            if (_hHookValue != 0)
            {
                bool ret = UnhookWindowsHookEx(_hHookValue);
                if (ret) _hHookValue = 0;
            }
        }
        //钩子事件内部调用,调用_clientMethod方法转发到客户端应用。
        private static int GetHookProc(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                //转换结构
                HookStruct hookStruct = (HookStruct)Marshal.PtrToStructure(lParam, typeof(HookStruct));

                if (_clientMethod != null)
                {
                    bool handle = false;
                    //调用客户提供的事件处理程序。
                    _clientMethod(hookStruct, out handle);
                    if (handle) return 1; //1:表示拦截键盘,return 退出
                }
            }
            return CallNextHookEx(_hHookValue, nCode, wParam, lParam);
        }
        #endregion
    }
}




//钩子的使用
private KeyboardHook _keyboardHook;//全局变量

private string inputKey;
public string InputKey
{
	get { return inputKey; }
	set
	{
		inputKey = value;
		NotifyOfPropertyChange(() => InputKey);
	}
}

internal bool inputFlag = false;
internal  bool isPress = false;      
internal string Password = "SKYWORTHQX";

//界面后台代码,或者绑定的源  
public void Loaded()
{
	//注册键盘钩子事件
	_keyboardHook = new KeyboardHook();
	_keyboardHook.InstallHook(this.KeyPress);
}

public void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
	//卸载钩子事件
	_keyboardHook.UninstallHook();
}

//键盘钩子   按F8输入密码,按Enter结束输入
public void KeyPress(KeyboardHook.HookStruct hookStruct, out bool handle)
{
	//截获F8
	if (hookStruct.vkCode == (int)System.Windows.Forms.Keys.F8)
	{
		handle = true;
		inputFlag = true;
		return;
	}

	if (inputFlag == false)
	{
		handle = false;
		return;
	}
	handle = true;
	if (hookStruct.vkCode == (int)System.Windows.Forms.Keys.Enter)
	{
		inputFlag = false;
		
		if (InputKey == Password)//密码正确显示对应的控件 或者 操作
		{
			IsOpenAdvance = Visibility.Visible;
		}
		InputKey = null;
	}
	else
	{
		if (isPress == false)
		{
			string Pass = ((System.Windows.Forms.Keys)hookStruct.vkCode).ToString();
			InputKey += Pass;
			isPress = true;
		}
		else
			isPress = false;
	   
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值