首页 WinForm/WPF WPF 一定时间内不动鼠标执行事件

WPF 一定时间内不动鼠标执行事件

作者:胡同里的砖头 围观群众:227 更新于:2023-12-10

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private DispatcherTimer mousePositionTimer; //长时间不操作该程序退回到登录界面的计时器
private Point mousePosition; //鼠标的位置
private int checkCount = 0; //检测鼠标位置的次数

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e); //启动程序
mousePosition = GetMousePoint(); //获取鼠标坐标

mousePositionTimer = new DispatcherTimer();
mousePositionTimer.Tick += new EventHandler(MousePositionTimedEvent);
mousePositionTimer.Interval = new TimeSpan(0, 0, 1); //每隔10秒检测一次鼠标位置是否变动
mousePositionTimer.Start();
}

private void MousePositionTimedEvent(object sender, EventArgs e)
{
if (!HaveUsedTo())
{
checkCount++; //检测到鼠标没移动,checkCount + 1
if (checkCount == 10)
{
checkCount = 0;
mousePositionTimer.Stop();
//重新启动此程序
System.Windows.Forms.Application.Restart();
Application.Current.Shutdown();
}

}
else
{
checkCount = 0; //检测到鼠标移动,重新计数
}
}

//判断鼠标是否移动
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;
}
}

  • 本文标题: WPF 一定时间内不动鼠标执行事件
  • 文章分类:【WinForm/WPF】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8