C# Winform程序如长时间不存在鼠标键盘输入操作后,关闭其他窗体,只显示主窗体

概述:Winform实现界面程序长时间不存在鼠标键盘输入操作后,关闭程序中显示的所有界面,除主界面外

方法一:使用窗体的WndProc函数

  • 1.在主窗体软件中使用消息过滤器,捕获软件内所有输入操作,即使用 

protected override void WndProc(ref Message m)

  • 2.设置定时器System.Windows.Forms.Time()
  • 3.判断时间间隔,如果时间间隔大于设定值,则获取所有打开的子窗体并关闭
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    System.Windows.Forms.Timer mTimer = new System.Windows.Forms.Timer();
    const int WM_KEYDOWN = 0x0100;
    private void Form1_Load(object sender, EventArgs e)
    {
         mTimer.Tick += T1_Tick;
         mTimer.Start();//开启定时器
    }
    void T1_Tick(object sender, EventArgs e)
    {
        if ((DateTime.Now - mRecordTime).TotalMinutes >= 1)//记录时间大于1分钟
        {
            int openFormNum = Application.OpenForms.Count;
            if(openFormNum > 1)
            {
                for(int i = 0; i < Application.OpenForms.Count; i++)
                {
                    Form item = Application.OpenForms[i];
                    if (item.Name != mainForm.Name && item.Text != mainForm.Text)//关闭不是主窗体的打开窗体
                    {
                        item.Close();
                        i--;
                    }
                }
            }
         }
    }
    protected override void WndProc(ref Message m)//拦截windows消息
    {
        if(m.Msg == WM_KEYDOWN)//判断是否为键盘按下
            mRecordTime = DateTime.Now;
        base.WndProc(ref m);
    }
}

 方法二:使用Application.AddMessageFilter(IMessageFilter)

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值