中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

在C#項目中如何管理全局鉤子

c#
小樊
91
2024-09-11 02:28:16
欄目: 編程語言

在C#項目中,可以使用全局鉤子(Global Hooks)來監視和捕獲系統范圍內的鍵盤和鼠標事件

  1. 首先,需要添加對System.Windows.FormsSystem.Runtime.InteropServices命名空間的引用。
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
  1. 定義一個類來處理全局鉤子。在這個類中,我們將使用P/Invoke來調用Windows API函數。
public class GlobalHook
{
    // 定義鉤子類型
    public enum HookType
    {
        WH_KEYBOARD_LL = 13,
        WH_MOUSE_LL = 14
    }

    // 定義鼠標鉤子結構體
    [StructLayout(LayoutKind.Sequential)]
    public struct MouseHookStruct
    {
        public Point pt;
        public int hwnd;
        public int wHitTestCode;
        public int dwExtraInfo;
    }

    // 定義鍵盤鉤子結構體
    [StructLayout(LayoutKind.Sequential)]
    public struct KeyboardHookStruct
    {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public int dwExtraInfo;
    }

    // 導入SetWindowsHookEx函數
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

    // 導入UnhookWindowsHookEx函數
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    // 導入CallNextHookEx函數
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    // 導入GetModuleHandle函數
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    // 定義鉤子回調委托
    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    // 定義鉤子事件
    public event EventHandler<MouseEventArgs> MouseEvent;
    public event EventHandler<KeyEventArgs> KeyEvent;

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

    public GlobalHook()
    {
        _hookProc = HookCallback;
    }

    // 安裝鉤子
    public void InstallHook(HookType hookType)
    {
        if (_hookID != IntPtr.Zero)
            return;

        IntPtr moduleHandle = GetModuleHandle(null);
        _hookID = SetWindowsHookEx((int)hookType, _hookProc, moduleHandle, 0);
    }

    // 卸載鉤子
    public void UninstallHook()
    {
        if (_hookID == IntPtr.Zero)
            return;

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

    // 鉤子回調函數
    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0)
        {
            if (_hookID != IntPtr.Zero)
            {
                switch ((HookType)_hookID.ToInt32())
                {
                    case HookType.WH_MOUSE_LL:
                        MouseHookStruct mouseData = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
                        MouseEvent?.Invoke(this, new MouseEventArgs(mouseData.pt));
                        break;

                    case HookType.WH_KEYBOARD_LL:
                        KeyboardHookStruct keyData = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                        KeyEvent?.Invoke(this, new KeyEventArgs(keyData.vkCode));
                        break;
                }
            }
        }

        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }
}
  1. 在你的應用程序中使用GlobalHook類來監聽鍵盤和鼠標事件。
public partial class MainForm : Form
{
    private readonly GlobalHook _globalHook;

    public MainForm()
    {
        InitializeComponent();

        _globalHook = new GlobalHook();
        _globalHook.MouseEvent += OnMouseEvent;
        _globalHook.KeyEvent += OnKeyEvent;
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // 安裝鉤子
        _globalHook.InstallHook(GlobalHook.HookType.WH_MOUSE_LL);
        _globalHook.InstallHook(GlobalHook.HookType.WH_KEYBOARD_LL);
    }

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

        // 卸載鉤子
        _globalHook.UninstallHook();
    }

    private void OnMouseEvent(object sender, MouseEventArgs e)
    {
        Console.WriteLine($"Mouse event: {e.Location}");
    }

    private void OnKeyEvent(object sender, KeyEventArgs e)
    {
        Console.WriteLine($"Key event: {e.KeyValue}");
    }
}

這樣,你就可以在C#項目中使用全局鉤子來監視和捕獲系統范圍內的鍵盤和鼠標事件了。請注意,全局鉤子可能會影響系統性能,因此在不需要時,務必及時卸載鉤子。

0
云南省| 介休市| 大连市| 郸城县| 罗田县| 汤阴县| 新巴尔虎右旗| 兴业县| 若尔盖县| 安泽县| 鄄城县| 娄烦县| 广昌县| 迭部县| 额尔古纳市| 吉木乃县| 隆林| 沧州市| 土默特左旗| 乐业县| 平谷区| 溧水县| 彰武县| 娱乐| 土默特右旗| 台前县| 临安市| 长治县| 花莲市| 察隅县| 蒲城县| 东山县| 繁峙县| 普格县| 封开县| 临猗县| 汶川县| 深州市| 湾仔区| 永清县| 雷波县|