猿问

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

}


汪汪一只猫
浏览 146回答 3
3回答

小唯快跑啊

简答从您发布的代码来看,您实际上只需要更改代码以禁用事件中的复选框并在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();    }}

蝴蝶不菲

这可以在不Timer显式使用的情况下完成。而是使用异步Task.Delay,这将简化代码并使其易于理解实际/领域意图。// Create extension method for better readabilitypublic 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();    }}

杨魅力

你应该使用Timer.SynchronizationObject
随时随地看视频慕课网APP
我要回答