C# 实现全局鼠标钩子操作以及发送键盘事件

全局钩子定义

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public static class GlobalMousePosition
    {
        #region 获取鼠标当前位置
        public const int WH_MOUSE_LL = 14;

        public enum MouseMessages
        {
            WM_MOUSEMOVE = 0x0200
        }

        public delegate int LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

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


        #region 点击事件
        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);

        // 模拟鼠标点击一次
        public static void SimulateMouseClick(int x, int y)
        {
            SetCursorPos(x, y);
            Thread.Sleep(100);  // 等待 100 毫秒,确保鼠标移动到指定位置

            // 模拟鼠标按下和释放操作(模拟点击)
            mouse_event(0x0002, x, y, 0, 0);  // 鼠标左键按下
            mouse_event(0x0004, x, y, 0, 0);  // 鼠标左键释放
        }
        #endregion

    }
}

winfrom窗体代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static WindowsFormsApp1.GlobalMousePosition;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private LowLevelMouseProc mouseProc;
        private IntPtr mouseHookId = IntPtr.Zero;
        public Form1()
        {
            InitializeComponent();
            this.TopMost = true;
        }

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

            // 注册全局鼠标钩子
            mouseProc = HookCallback;
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                mouseHookId = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            // 取消注册全局鼠标钩子
            UnhookWindowsHookEx(mouseHookId);
        }

        private int HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
            {
                // 获取鼠标位置
                Point mousePosition = Cursor.Position;

                // 更新你的全局记录逻辑,比如将当前鼠标位置保存到全局变量或日志中
                // ...
                labelMousePosition.Text = string.Format("当前鼠标位置:X={0}, Y={1}", mousePosition.X, mousePosition.Y);
            }

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

        private void button1_Click(object sender, EventArgs e)
        {
            Clipboard.Clear(); // 清空剪贴板
            int x = int.Parse(this.x.Text);
            int y = int.Parse(this.y.Text);
            string text = this.textbox.Text;
            Clipboard.SetText(text);
            Thread.Sleep(100);
            SimulateMouseClick(x, y);
            Thread.Sleep(100);
            SendKeys.Send("^(v)");
            Thread.Sleep(100);
            SendKeys.Send("\t");
        }
    }
}

效果截图:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C#全局鼠标钩子的完整源码: 首先,创建一个名为MouseHook的类,实现IMouseHook接口: ```csharp using System; using System.Runtime.InteropServices; namespace MouseHookExample { public class MouseHook : IMouseHook { private const int WH_MOUSE_LL = 14; private const int WM_LBUTTONDOWN = 0x0201; private const int WM_RBUTTONDOWN = 0x0204; private LowLevelMouseProc _proc; private IntPtr _hookId = IntPtr.Zero; public event EventHandler<MouseEventArgs> LeftButtonDown; public event EventHandler<MouseEventArgs> RightButtonDown; public void Start() { _proc = HookCallback; _hookId = SetHook(_proc); } public void Stop() { UnhookWindowsHookEx(_hookId); _hookId = IntPtr.Zero; } private IntPtr SetHook(LowLevelMouseProc proc) { using (var curProcess = System.Diagnostics.Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && (wParam == (IntPtr)WM_LBUTTONDOWN || wParam == (IntPtr)WM_RBUTTONDOWN)) { var hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); var args = new MouseEventArgs(hookStruct.pt.x, hookStruct.pt.y); if (wParam == (IntPtr)WM_LBUTTONDOWN) { LeftButtonDown?.Invoke(this, args); } else if (wParam == (IntPtr)WM_RBUTTONDOWN) { RightButtonDown?.Invoke(this, args); } } return CallNextHookEx(_hookId, nCode, wParam, lParam); } private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc 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); [StructLayout(LayoutKind.Sequential)] private struct POINT { public int x; public int y; } [StructLayout(LayoutKind.Sequential)] private struct MSLLHOOKSTRUCT { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo; } } } ``` 接下来,定义一个名为MouseEventArgs的类,用于传递鼠标事件的参数: ```csharp using System; namespace MouseHookExample { public class MouseEventArgs : EventArgs { public int X { get; } public int Y { get; } public MouseEventArgs(int x, int y) { X = x; Y = y; } } } ``` 最后,定义一个名为IMouseHook的接口,用于规范MouseHook类的实现: ```csharp using System; namespace MouseHookExample { public interface IMouseHook { event EventHandler<MouseEventArgs> LeftButtonDown; event EventHandler<MouseEventArgs> RightButtonDown; void Start(); void Stop(); } } ``` 现在,我们可以在其他类中使用该鼠标钩子: ```csharp using System; namespace MouseHookExample { class Program { static void Main(string[] args) { var mouseHook = new MouseHook(); mouseHook.LeftButtonDown += (sender, e) => Console.WriteLine($"Left button down at ({e.X}, {e.Y})"); mouseHook.RightButtonDown += (sender, e) => Console.WriteLine($"Right button down at ({e.X}, {e.Y})"); mouseHook.Start(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); mouseHook.Stop(); } } } ``` 现在,当用户按下鼠标左键或右键时,程序将在控制台中输出相应的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值