首页 > 解决方案 > 当 CheckBox 未选中时,使其无法在特定时间 C#

问题描述

我正在开发防病毒程序和实时保护面板上我想要复选框,例如未选中“恶意软件保护”复选框以使其在 15 分钟内无法启用,然后再次启用它以防止垃圾邮件。如果有人可以帮助我,那就太好了

我尝试过,Thread.Sleep()但它会停止整个应用程序,我尝试过使用计时器,但我认为我做错了。

这是计时器的代码

private void checkBox1_CheckStateChanged(object sender, EventArgs e)
{
    if (this.checkBox1.Checked)
    {
        this.checkBox1.Text = "On";
        // these two pictureboxes are for "You are (not) protected"
        // picture
        picturebox1.Show();
        pictureBox5.Hide();
        timer1.Stop();
    }
    else
    {
        this.checkBox1.Text = "Off";
        // this is the problem
        timer1.Start();
        this.checkBox1.Enabled = true;
        pictureBox1.Hide();
        pictureBox5.Show();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.checkBox1.Enabled = false;
}

标签: c#visual-studiowinforms

解决方案


简答

从您发布的代码来看,您实际上只需要更改代码以禁用事件中的复选框并在CheckChanged事件中启用timer1_Tick(以及事件Stop中的计时器Tick)。

完整答案

Winforms 有一个Timer可以用于此的控件。将 aTimer放到设计器上后,将Interval属性设置为启用复选框之前要等待的毫秒数(1秒是1000毫秒,所以 15 分钟是15min * 60sec/min * 1000ms/sec,或900,000ms)。然后双击它以创建Tick事件处理程序(或在您的事件中添加一个,Form_Load如下所示)。

接下来,CheckChanged如果未选中该复选框,则禁用该复选框并启动计时器。

然后,在Tick事件中,只需启用复选框(请记住,此事件在经过毫秒后触发Interval)并停止计时器。

例如:

private void Form1_Load(object sender, EventArgs e)
{
    // These could also be done in through designer & property window instead
    timer1.Tick += timer1_Tick; // Hook up the Tick event
    timer1.Interval = (int) TimeSpan.FromMinutes(15).TotalMilliseconds; // Set the Interval
}

private void timer1_Tick(object sender, EventArgs e)
{
    // When the Interval amount of time has elapsed, enable the checkbox and stop the timer
    checkBox1.Enabled = true;
    timer1.Stop();
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (!checkBox1.Checked)
    {
        // When the checkbox is unchecked, disable it and start the timer
        checkBox1.Enabled = false;
        timer1.Start();
    }
}

推荐阅读