3 回答

TA貢獻1863條經驗 獲得超2個贊
簡答
從您發布的代碼來看,您實際上只需要更改代碼以禁用事件中的復選框并在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();
}
}

TA貢獻1810條經驗 獲得超4個贊
這可以在不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 回答
- 0 關注
- 170 瀏覽
添加回答
舉報