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

时间:2015-06-08 10:05:39

标签: c# winforms

我正在尝试使用工具箱中的计时器禁用我在一段时间不活动后使用的所有按钮。我现在可以通过禁用

中的相关按钮来实现它
 private void timer1_Tick(object sender, EventArgs e)

但无论活动或不活动,都会在十秒内禁用。 定时器是否可以在没有活动10秒后才能工作?

这是我正在使用的代码。

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;
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

只需将以下事件添加到可能被点击并被计为“有效”的每个按钮:

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

...

button1.Click += ResetTimer;

Winforms中的Timer没有Reset方法(也没有任何其他计时器类),因此您必须先停止它然后重新启动它。

答案 1 :(得分:0)

解决方案1:

每次用户点击任何按钮时重置时间。

解决方案2 :(不推荐)

拥有一个全局变量LastActiveTime,每次有人点击任何一个 按钮:

 LastActiveTime = DateTime.Now()

如果非活动时间超过10,并行运行的定时器/线程将每秒检查一次  第二,并将相应地做。