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分钟
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [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;
        }
    }
}

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值