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;