在 C# Windows Forms 應用中,需要一個 Timer 組件實現:窗口啟動後 75 秒自動關閉,並在 Label 上實時顯示剩餘秒數倒計時。
using System;
using System.Windows.Forms;
namespace CountdownCloseDemo
{
public partial class MainForm : Form
{
private int _remainingSeconds = 75;
private Timer _countdownTimer;
public MainForm()
{
InitializeComponent();
InitializeCountdownTimer();
}
private void InitializeCountdownTimer()
{
// 1. 創建並配置 Timer
_countdownTimer = new Timer();
_countdownTimer.Interval = 1000; // 1 秒觸發一次
_countdownTimer.Tick += CountdownTimer_Tick;
// 2. 初始化界面顯示
lblCountdown.Text = _remainingSeconds.ToString();
// 3. 啟動計時器
_countdownTimer.Start();
}
private void CountdownTimer_Tick(object sender, EventArgs e)
{
_remainingSeconds--;
lblCountdown.Text = _remainingSeconds.ToString();
if (_remainingSeconds <= 0)
{
_countdownTimer.Stop();
_countdownTimer.Dispose();
this.Close(); // 或 this.Dispose() 釋放資源
}
}
// 可選:窗口關閉時確保釋放 Timer
protected override void OnFormClosed(FormClosedEventArgs e)
{
if (_countdownTimer != null)
{
_countdownTimer.Stop();
_countdownTimer.Dispose();
}
base.OnFormClosed(e);
}
}
}
System.Windows.Forms.Timer(UI 線程定時器),而非 System.Timers.Timer 或 System.Threading.Timer,避免跨線程訪問 UI 控件導致異常。1000 毫秒 = 1 秒,放在構造函數或 Load 事件中設置。Tick 事件中遞減計數器,更新 Label 文本,歸零時停止 Timer 並關閉窗口。Stop() 和 Dispose() 防止內存洩漏。private void btnPauseResume_Click(object sender, EventArgs e)
{
if (_countdownTimer.Enabled)
{
_countdownTimer.Stop();
btnPauseResume.Text = "繼續";
}
else
{
_countdownTimer.Start();
btnPauseResume.Text = "暫停";
}
}
private void CountdownTimer_Tick(object sender, EventArgs e)
{
_remainingSeconds--;
lblCountdown.Text = _remainingSeconds.ToString();
if (_remainingSeconds <= 10) // 最後 10 秒提示
{
lblCountdown.ForeColor = Color.Red;
}
if (_remainingSeconds <= 0)
{
_countdownTimer.Stop();
var result = MessageBox.Show("倒計時結束,確定要關閉窗口嗎?", "確認",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
this.Close();
else
{
_remainingSeconds = 10; // 重置 10 秒
_countdownTimer.Start();
}
}
}
private async void MainForm_Load(object sender, EventArgs e)
{
for (int i = 75; i >= 0; i--)
{
lblCountdown.Text = i.ToString();
if (i == 0) break;
await Task.Delay(1000);
}
this.Close();
}
此寫法更簡潔,但需注意異常處理與窗口關閉時的任務取消。
_countdownTimer.Start() 導致不觸發 TickThread.Sleep 阻塞 UI 線程,界面凍結Application.Exit() 而非 this.Close(),可能導致資源未正確釋放