取消选中CheckBox时,使其无法在特定时间C#

时间:2019-01-16 16:39:43

标签: c# visual-studio winforms

我正在使用防病毒程序和实时保护面板上的复选框,例如,当未选中“恶意软件防护”复选框以使其在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;
}

4 个答案:

答案 0 :(得分:1)

简短回答

从您发布的代码来看,实际上只需要在CheckChanged事件中将代码更改为 disable 复选框,然后在其中 enable timer1_Tick事件(以及Stop事件中的计时器Tick)。

完整答案

Winforms具有一个Timer控件,您可以使用此控件。将Timer放到设计器上之后,将Interval属性设置为要启用复选框之前要等待的毫秒数(1秒是1000毫秒,因此15分钟为15分钟* 60秒/分钟* 1000毫秒/秒或900,000毫秒)。然后双击它以创建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();
    }
}

答案 1 :(得分:0)

您可以使用task.Delay()禁用并启用它。继续()。这将创建一个新线程,延迟完成后将触发该线程。您需要使其成为线程安全的,而winforms本身不是线程安全的

答案 2 :(得分:0)

无需显式使用Timer即可完成此操作。而是使用异步Task.Delay,这将简化代码并使其易于理解实际/领域意图。

// Create extension method for better readability
public class ControlExtensions
{
    public static Task DisableForSeconds(int seconds)
    {
        control.Enabled = false;
        await Task.Delay(seconds * 1000);
        control.Enabled = true;
    }
}

private void checkBox1_CheckStateChanged(object sender, EventArgs e)
{
    var checkbox = (CheckBox)sender;
    if (checkbox.Checked)
    {
        checkbox.Text = "On";
        picturebox1.Show();
        pictureBox5.Hide();
    }
    else
    {
        checkbox.Text = "Off";
        checkbox.DisableForSeconds(15 * 60);
        pictureBox1.Hide();
        pictureBox5.Show();
    }
}

答案 3 :(得分:-1)

您应该使用Timer.SynchronizationObject