在使用计时器静止10秒后禁用按钮

本文关键字:10秒 按钮 静止 计时器 | 更新日期: 2023-09-27 17:54:04

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

中的相关按钮来让它工作
 private void timer1_Tick(object sender, EventArgs e)

,但无论活动与否,它都会在10秒内禁用。计时器是否可能在没有活动的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;
}

任何帮助都将非常感激。

在使用计时器静止10秒后禁用按钮

只需将以下事件添加到每个可能被点击并被计数为'活动'的按钮:

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

Timer在Winforms没有Reset方法(也没有任何其他定时器类),所以你必须先停止它,然后再开始。

方案一:

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

方案2:(不推荐)

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

 LastActiveTime = DateTime.Now()

如果非活动时间超过10,并行运行计时器/线程将每秒检查一次第二步: