C# 监测指定时间未操作后 锁定或退出程序

  • 前几天遇见客户提出这样一个需求:要求程序在30分钟未使用的时候就锁定程序
  • 然后就有了几种处理思路:
  1. 使用计时器倒计时,在所有有交互操作的地方加上重置计时器的代码。确定用于很多界面的程序就不现实了。
  2. 通过数据库登陆记录表,在表里增加一个最后操作时间,在所有SQL操作方法里重置这个时间为SQL执行时间,客户端开线程轮训这个时间,与当前时间差距为30分钟时,锁定或退出。确定,有点耗资源。
  3. 使用HOOK监测电脑全局鼠键操作的方法,30分钟无操作,锁定或退出。人离开时没问题,但如果是操作别的程序,那逻辑就不正确了
  4. 使用Application.AddMessageFilter() ,这个方法将截获本程序向系统发出的消息,和挂钩HOOK是不一样的。HOOK是监测电脑全局的,而这个是监测本程序的。(推荐)
       
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.UserSkins;
using DevExpress.Skins;
using DevExpress.LookAndFeel;

namespace MAP
{
    static class Program
    {
        public static int tickcount = 30;//30分钟
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            BonusSkins.Register();
            SkinManager.EnableFormSkins();
            UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");
         

            MessageFilter MessageFilter = new MAP.MessageFilter();
            Application.AddMessageFilter(MessageFilter);

            Timer timer = new Timer();
            timer.Interval = 60000;//1分钟
            timer.Tick += timer_Tick;
            timer.Start();

            Application.Run(new Form1());
        }

        static void timer_Tick(object sender, EventArgs e)
        {
            tickcount--;
            if (tickcount == 0)
            {
                Application.Restart();
            }
        }
    }

    internal class MessageFilter : IMessageFilter
    {
        public bool PreFilterMessage(ref Message m)
        {
            //如果检测到有鼠标或则键盘的消息,则使计数为0.....
            if (m.Msg == 0x0200 || m.Msg == 0x0201 || m.Msg == 0x0204 || m.Msg == 0x0207)
            {
                MAP.Program.tickcount = 30;
            }

            return false;
        }
    }
}

你可能感兴趣的:(C# 监测指定时间未操作后 锁定或退出程序)