c#

如何编写高效的C#全局钩子代码

小樊
83
2024-09-11 02:26:34
栏目: 编程语言

在C#中,要编写高效的全局钩子代码,您需要使用Windows API函数SetWindowsHookEx

  1. 首先,引入所需的命名空间:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
  1. 定义钩子类型和委托:
public class GlobalHook
{
    public enum HookType : int
    {
        WH_KEYBOARD_LL = 13,
        WH_MOUSE_LL = 14
    }

    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
}
  1. 导入Windows API函数:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, GlobalHook.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);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
  1. 创建钩子并处理事件:
public class GlobalHook
{
    // ...

    private IntPtr _hookID = IntPtr.Zero;
    private GlobalHook.HookProc _hookProc;

    public void SetHook(HookType hookType, GlobalHook.HookProc hookProc)
    {
        if (_hookID != IntPtr.Zero) return;

        _hookProc = hookProc;
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            _hookID = SetWindowsHookEx((int)hookType, _hookProc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    public void RemoveHook()
    {
        if (_hookID == IntPtr.Zero) return;

        UnhookWindowsHookEx(_hookID);
        _hookID = IntPtr.Zero;
    }

    public IntPtr OnHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0) return CallNextHookEx(_hookID, nCode, wParam, lParam);

        // 在此处处理钩子事件,例如按键或鼠标事件
        // ...

        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }
}
  1. 使用钩子:
public partial class MainForm : Form
{
    private GlobalHook _globalHook;

    public MainForm()
    {
        InitializeComponent();

        _globalHook = new GlobalHook();
        _globalHook.SetHook(GlobalHook.HookType.WH_KEYBOARD_LL, KeyboardHookCallback);
    }

    private IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0)
        {
            Keys key = (Keys)Marshal.ReadInt32(lParam);
            Console.WriteLine($"Key: {key}, Param: {wParam}");
        }

        return _globalHook.OnHookCallback(nCode, wParam, lParam);
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        _globalHook.RemoveHook();
    }
}

这样,您就可以编写一个高效的C#全局钩子代码。请注意,全局钩子可能会影响系统性能,因此请谨慎使用。

0
看了该问题的人还看了