第三方钩子 MouseKeyHook 监控鼠标键盘事件

 public partial class Form4 : Form
    {
        private static IKeyboardMouseEvents m_GlobalHook;
        public Form4()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 初始化全局鼠标和键盘事件钩子
            m_GlobalHook = Hook.GlobalEvents();

            // 订阅鼠标事件
            m_GlobalHook.MouseDownExt += GlobalHookMouseDown;
            m_GlobalHook.MouseUpExt += GlobalHookMouseUp;
            m_GlobalHook.MouseMoveExt += GlobalHookMouseMove;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 卸载事件钩子
            m_GlobalHook.MouseDownExt -= GlobalHookMouseDown;
            m_GlobalHook.MouseUpExt -= GlobalHookMouseUp;
            m_GlobalHook.MouseMoveExt -= GlobalHookMouseMove;

            // 销毁全局钩子
            m_GlobalHook.Dispose();
        }

        private static void GlobalHookMouseDown(object sender, MouseEventExtArgs e)
        {
            Console.WriteLine($"Mouse Down: {e.Button}, X: {e.X}, Y: {e.Y}");
        }

        private static void GlobalHookMouseUp(object sender, MouseEventExtArgs e)
        {
            Console.WriteLine($"Mouse Up: {e.Button}, X: {e.X}, Y: {e.Y}");
        }

        private static void GlobalHookMouseMove(object sender, MouseEventExtArgs e)
        {
            Console.WriteLine($"Mouse Move: X: {e.X}, Y: {e.Y}");
        }
    }

你可能感兴趣的:(C#,钩子,c#)