/// <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;
}
}