WPF在ViewModel中监测鼠标移动

该代码示例展示了如何创建一个名为MouseMonitorHelper的类来监测鼠标是否在屏幕上移动。通过使用WindowsAPI的GetCursorPos方法获取鼠标位置,并结合DispatcherTimer定时器,每10秒检查一次鼠标是否移动。如果在一分钟内鼠标未移动,程序将执行特定操作,如隐藏关闭按钮和鼠标。
摘要由CSDN通过智能技术生成

1.首先需要创建鼠标移动帮助类

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

namespace Common
{
    public class MouseMonitorHelper
    {
        private static Point mousePosition;    //鼠标的位置
        public static int CheckCount;   //检测鼠标位置的次数

        //判断鼠标是否移动        
        public static 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 static Point GetMousePoint()
        {
            MPoint mpt = new MPoint();
            GetCursorPos(out mpt);
            Point p = new Point(mpt.X, mpt.Y);
            return p;
        }
    }
}

2.在VeiwModel创建定时器进行监测

       //构造函数中
       {
            this.Timer_MouseMove = new DispatcherTimer();
            this.Timer_MouseMove.Tick += new EventHandler(Timer_MouseMove_Tick);
            this.Timer_MouseMove.Interval = new TimeSpan(0, 0, 10);
            this.Timer_MouseMove.Start();
        }

        private void Timer_MouseMove_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!MouseMonitorHelper.HaveUsedTo())
                {
                    MouseMonitorHelper.CheckCount++;
                    if (MouseMonitorHelper.CheckCount == 6)//一分钟达到关闭时间
                    {
                        MouseMonitorHelper.CheckCount = 0;
                        // 关闭按钮隐藏、鼠标隐藏
                        //this.cnsExist.Visibility = Visibility.Hidden;
                        Mouse.OverrideCursor = Cursors.None;
                        //通过用隐藏鼠标的方式来提示一分钟鼠标没移动位置
                    }
                }
                else
                {
                    MouseMonitorHelper.CheckCount = 0;
                }
            }
            catch
            {
                throw new NotImplementedException();
            }
        }

        private DispatcherTimer Timer_MouseMove;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值