c# HookProc 钩子

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class LocalKeyboardHook
{
    // 定义钩子委托
    private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    // 钩子类型
    private const int WH_KEYBOARD_LL = 13;

    // 声明钩子的函数
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

    // 声明卸载钩子的函数
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    // 声明调用下一个钩子的函数
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    private const int WM_KEYDOWN = 0x0100;
    private const int WM_KEYUP = 0x0101;

    private HookProc hookDelegate;
    private IntPtr hookId = IntPtr.Zero;

    public event KeyEventHandler KeyDown;
    public event KeyEventHandler KeyUp;

    public LocalKeyboardHook()
    {
        hookDelegate = HookCallback;
        hookId = SetHook(hookDelegate);
    }

    public void Dispose()
    {
        UnhookWindowsHookEx(hookId);
    }

    private IntPtr SetHook(HookProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0)
        {
            if (wParam == (IntPtr)WM_KEYDOWN)
            {
                KeyEventArgs keyEventArgs = CreateKeyEventArgs(lParam);
                KeyDown?.Invoke(this, keyEventArgs);
            }
            else if (wParam == (IntPtr)WM_KEYUP)
            {
                KeyEventArgs keyEventArgs = CreateKeyEventArgs(lParam);
                KeyUp?.Invoke(this, keyEventArgs);
            }
        }

        return CallNextHookEx(hookId, nCode, wParam, lParam);
    }

    private KeyEventArgs CreateKeyEventArgs(IntPtr lParam)
    {
        int keyCode = Marshal.ReadInt32(lParam);
        Keys key = (Keys)keyCode;
        int keyData = (int)key;
        int scanCode = (int)((uint)lParam >> 16 & 0xFF);
        int flags = (int)((uint)lParam >> 24);

        return new KeyEventArgs(keyData | (scanCode << 16) | (flags << 24));
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

调用

using System;
using System.Windows.Forms;

public partial class MainForm : Form
{
    private LocalKeyboardHook keyboardHook;

    public MainForm()
    {
        InitializeComponent();
        keyboardHook = new LocalKeyboardHook();
        keyboardHook.KeyDown += KeyboardHook_KeyDown;
    }

    private void KeyboardHook_KeyDown(object sender, KeyEventArgs e)
    {
        // 处理键盘按键按下事件
        MessageBox.Show($"Key Down: {e.KeyCode}");
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        // 清理资源
        keyboardHook.Dispose();
        base.OnFormClosing(e);
    }
}

你可能感兴趣的:(c#)