简体   繁体   English

在使用计时器不活动10秒后禁用按钮

[英]Disable buttons after after 10 seconds of inactivity using timer

I am trying to disable all buttons I am using after a time period of inactivity using the timer from toolbox. 我试图在一段时间不活动之后使用工具箱中的计时器禁用我正在使用的所有按钮。 I can currently get it to work by just disabling the relevant buttons in 我目前可以通过禁用其中的相关按钮来使其工作

 private void timer1_Tick(object sender, EventArgs e)

but this disables in ten seconds regardless of activity or inactivity. 但这会在十秒钟内禁用,无论是否处于活动状态。 Is it possible for the timer to work only after 10 seconds of no activity? 计时器是否可以仅在10秒钟无活动后才能工作?

Here is the code I am using. 这是我正在使用的代码。

private void timer1_Tick(object sender, EventArgs e) {
    button1.Enabled = false;
    button2.Enabled = false;
    button3.Enabled = false;
    button4.Enabled = false;
    button5.Enabled = false;
    button6.Enabled = false;
    button7.Enabled = false;
    button8.Enabled = false;
    button9.Enabled = false;
    button10.Enabled = false;
    button11.Enabled = false;
    button12.Enabled = false;
    button13.Enabled = true;
    button14.Enabled = true;
    button14.Visible = false;
    button15.Enabled = true;
    button15.Visible = false;
    button17.Enabled = false;
    button17.Visible = false;
    button18.Visible = false;
    button19.Visible = false;
    button20.Enabled = false;
    textBox1.Visible = false;
    textBox2.Visible = false;
    textBox3.Visible = false;
    textBox4.Visible = false;
    checkBox1.Visible = false;
    checkBox2.Visible = false;
    label15.Visible = false;
    label16.Visible = false;
    label21.Visible = false;
}

Any help would be greatly appreciated. 任何帮助将不胜感激。

Just add the following event to each button that might be clicked and be counted as 'active': 只需将以下事件添加到每个可能被单击并计为“活动”的按钮:

public void ResetTimer(object sender, EventArgs e)
{
    timer.Stop();
    timer.Start();
}

...

button1.Click += ResetTimer;

The Timer in Winforms doesn't have a Reset method (nor does any of the other timer classes), so you'll have to stop it first and then start it again. Winforms中的Timer没有Reset方法(其他任何计时器类也没有),因此您必须先将其停止然后再次启动。

Solution 1: 解决方案1:

Reset Time every time user click any button. 每次用户单击任何按钮时的重置时间。

Solution 2 : ( Not Recommended ) 解决方案2 :(不推荐)

Have a global variable LastActiveTime, Every-time somebody clicks any button : 有一个全局变量LastActiveTime,每次有人单击任何按钮:

 LastActiveTime = DateTime.Now()

Parallel running Timer/Thread will check every second if inactive time is more than 10 second and will do accordingly. 如果不活动时间超过10秒,则并行运行的计时器/线程将每秒检查一次,并会相应地进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM