WPF 长时间无鼠标键盘操作自动回到主页

WPF 长时间无键鼠操作后自动执行某些操作

因需要在页面长时间无操作后自动返回首页,在这里记录一下。
利用Windows的API:GetLastInputInfo

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

namespace WpfApplication1
{
    /// 
    /// App.xaml 的交互逻辑
    /// 
    public partial class App : Application
    {
        private DispatcherTimer mouseOrKeyboardOpTimer;
        private readonly static int defaultCheckCount = 10; // 设置默认时间是10s

        public static int checkCount = defaultCheckCount; // 可以在其他页面也获取计数,显示跳转倒计时

        /// 
        /// 重载启动方法
        /// 
        /// 
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e); 
            mouseOrKeyboardOpTimer = new DispatcherTimer(); 
            mouseOrKeyboardOpTimer.Tick += new EventHandler(mouseOrKeyboardOpTimer_Tick);
            mouseOrKeyboardOpTimer.Interval = new TimeSpan(0, 0, 1);
            mouseOrKeyboardOpTimer.Start();
        }

        /// 
        /// 处理键鼠操作
        /// 
        /// 
        /// 
        void mouseOrKeyboardOpTimer_Tick(object sender, EventArgs e)
        {
            if (HaveUsedTo())
            {
                if (--checkCount == 0)
                {
                    checkCount = defaultCheckCount;
                    mouseOrKeyboardOpTimer.Stop();
                    // 跳转到其他页面或者其他操作
                    mouseOrKeyboardOpTimer.Start();
                }
            }
            else
            {
                checkCount = defaultCheckCount;
            }
        }

        /// 
        /// 未操作时间超过1s后才开始计数
        /// 
        /// 返回未操作时间是否超过1s
        private bool HaveUsedTo()
        {
            return GetNoMouseOrKeyboardOpTime() / 1000 > 1;
        }


        /// 
        /// Windows API 获取上次键鼠操作时间间隔
        /// 
        /// 
        /// 
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref PLASTINPUTINFO plii);

        private static long GetNoMouseOrKeyboardOpTime()
        {
            PLASTINPUTINFO lastInputInfo = new PLASTINPUTINFO();
            lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
            if (!GetLastInputInfo(ref lastInputInfo)) return 0;
            return Environment.TickCount - lastInputInfo.dwTime;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct PLASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }
    }
}

你可能感兴趣的:(C#)