C#开发winform&wpf后台捕获鼠标移动事件

做 WPF和winform的时候,可以在界面上设置鼠标移动事件来检测鼠标移动,如果项目为后期改造这样做的话改动量很大,今天通过另外一种后台调用windows api的方式进行快速捕获和触发,提高开发效率分享给大家。

csharp 复制代码
  /// <summary>
    /// 鼠标移动帮助类
    /// </summary>
    public class MouseMoveHelper:IDisposable
    {
        public MouseMoveHelper()
        {

        }

        public void Dispose()
        {
            try
            {
                if (mousePositionTimer != null)
                {
                    mousePositionTimer.Stop();
                    deactivatedTimer.Stop();
                    mousePositionTimer = null;
                    deactivatedTimer = null;
                }
            }
            catch (Exception ex)
            {

            }
        }

        public Action<NoOperationEvent> OK;


        #region 监测是否有用户操作

        private DispatcherTimer mousePositionTimer;    //长时间不操作该程序退回到登录界面的计时器
        private Point mousePosition;    //鼠标的位置
        private int checkCount = 0;   //检测鼠标位置的次数

        private DispatcherTimer deactivatedTimer;   //当焦点不在此程序上时计时器


        public void Start()
        {
            mousePosition = GetMousePoint();  //获取鼠标坐标

            if (mousePositionTimer==null)
            {
                mousePositionTimer = new DispatcherTimer();
                mousePositionTimer.Tick += new EventHandler(MousePositionTimedEvent);
                mousePositionTimer.Interval = new TimeSpan(0, 0, 1);     //每隔10秒检测一次鼠标位置是否变动
            }
            mousePositionTimer.Start();
            if (deactivatedTimer == null)
            {
                deactivatedTimer = new DispatcherTimer();
                deactivatedTimer.Tick += new EventHandler(deactivatedTimer_Tick);
                deactivatedTimer.Interval = new TimeSpan(0, 0, 10);   //如果焦点不在此程序中时,过10s程序自动重启
            }
        }

        bool isMoved = true;
        // 倒计时延迟数
        int maxDelayCount = 1;

        private void MousePositionTimedEvent(object sender, EventArgs e)
        {
            
            if (!HaveUsedTo())
            {
                checkCount++;    //检测到鼠标没移动,checkCount + 1  
                if (checkCount == maxDelayCount)
                {
                    checkCount = 0;
                    //长时间无人操作
                    if (isMoved)
                    {
                        isMoved = false;
                        OK?.Invoke(new NoOperationEvent() { Message = "检测到无鼠标移动", CurrentMouseState = NoOperationEvent.MouseState.standstill });
                    }
                }
            }
            else
            {
                OK?.Invoke(new NoOperationEvent() { Message = "检测到鼠标移动", CurrentMouseState = NoOperationEvent.MouseState.move });
                checkCount = 0;     //检测到鼠标移动,重新计数
                isMoved=true;
            }
        }

        private void deactivatedTimer_Tick(object sender, EventArgs e)
        {
            deactivatedTimer.Stop();
            //长时间无人操作
            //Messenger.Default.Send<string>("focus", "DoFocus");
        }


        //判断鼠标是否移动
        private bool HaveUsedTo()
        {
            Point point = GetMousePoint();
            if (point == mousePosition)
            {
                return false;
            }
            mousePosition = point;
            return true;
        }


        [StructLayout(LayoutKind.Sequential)]
        private struct MPoint
        {
            public int X;
            public int Y;

            public MPoint(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool GetCursorPos(out MPoint mpt);

        /// 获取当前屏幕鼠标位置   
        public Point GetMousePoint()
        {
            MPoint mpt = new MPoint();
            GetCursorPos(out mpt);
            Point p = new Point(mpt.X, mpt.Y);
            return p;
        }

        
        #endregion
    }

程序调用

csharp 复制代码
            var MouseMoveHelper = new MouseMoveHelper();
            MouseMoveHelper.OK = CheckMouseState;
             MouseMoveHelper.Start();

一般在顶级父类里面初始化的时候进行处理即可

相关推荐
董先生_ad986ad2 小时前
C# 中的 `lock` 关键字本质
开发语言·c#
爱编程的鱼6 小时前
C# 枚举(Enum)声明与使用详解
java·windows·c#
冰茶_8 小时前
C#中常见的设计模式
java·开发语言·microsoft·设计模式·微软·c#·命令模式
chegan9 小时前
用c#从头写一个AI agent,实现企业内部自然语言数据统计分析(二)-数据结构和代码分析方法
ai·c#·agent
煤烦恼9 小时前
Kafka 命令行操作与 Spark-Streaming 核心编程总结
c#·linq
电子科技圈11 小时前
XMOS空间音频——在任何设备上都能提供3D沉浸式空间音频且实现更安全地聆听
经验分享·设计模式·性能优化·计算机外设·音视频
Zhen (Evan) Wang11 小时前
.NET 6 + Dapper + User-Defined Table Type
sqlserver·c#·.net·wpf
FAREWELL0007512 小时前
C#进阶学习(十四)反射的概念以及关键类Type
开发语言·学习·c#·反射·type
FAREWELL0007512 小时前
C#进阶学习(十三)C#中的预处理器指令
开发语言·学习·c#·预处理指令
qq_2979080113 小时前
c#简易超市充值卡程序充值消费查余额
经验分享·sqlserver·开源·c#·.net·开源软件