C# 钩子,监控键盘消息。

这篇博客详细介绍了如何使用C#编程实现键盘钩子,监控键盘输入消息。通过`SetWindowsHookEx`等WinAPI函数设置和移除钩子,并在回调函数中处理键盘事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        IntPtr CurrHook;        //得到钩子句柄

       
        [DllImport("kernel32.dll")]
        public static extern int GetCurrentThreadId();      //得到线程ID

        [DllImport("user32.dll")]
        //--------开始装钩子HookType:钩子类型,backCall:回调委托,MyNull:当前实例句柄,ThreadId:线程ID
        public static extern IntPtr SetWindowsHookEx(int HookType, KeyBackCall backCall, IntPtr MyNull, int ThreadId);

        [DllImport("user32.dll")]
        public static extern IntPtr CallNextHookEx(IntPtr CurrHook, int nCode, IntPtr wParam, IntPtr lParam);


        [DllImport("user32.dll")]
        public static extern void UnhookWindowsHookEx(IntPtr CurrHook);

        //----回调的委托
        public delegate IntPtr KeyBackCall(int nCode, IntPtr wParam, IntPtr lParam);

        //--------委托事件
        public IntPtr KeyBackCallEvent(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode > 0)
            {
                MessageBox.Show(wParam.ToString());
                return CallNextHookEx(CurrHook, nCode, wParam, lParam);
            }
            return CallNextHookEx(CurrHook, nCode, wParam, lParam);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            CurrHook = SetWindowsHookEx(2, new KeyBackCall(KeyBackCallEvent), IntPtr.Zero, GetCurrentThreadId());          
           
        }

 

        private void button2_Click(object sender, EventArgs e)
        {
            UnhookWindowsHookEx(CurrHook);

        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值