首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# WinForms 實現 75 秒倒計時自動關閉窗口

     編輯:程式設計綜合問答

需求分析

在 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);
        }
    }
}

關鍵點解析

  1. Timer 選擇:使用 System.Windows.Forms.Timer(UI 線程定時器),而非 System.Timers.Timer 或 System.Threading.Timer,避免跨線程訪問 UI 控件導致異常。
  2. Interval 設置:1000 毫秒 = 1 秒,放在構造函數或 Load 事件中設置。
  3. 倒計時邏輯:在 Tick 事件中遞減計數器,更新 Label 文本,歸零時停止 Timer 並關閉窗口。
  4. 資源釋放:調用 Stop() 和 Dispose() 防止內存洩漏。

進階增強功能

1. 暫停/繼續按鈕

private void btnPauseResume_Click(object sender, EventArgs e)
{
    if (_countdownTimer.Enabled)
    {
        _countdownTimer.Stop();
        btnPauseResume.Text = "繼續";
    }
    else
    {
        _countdownTimer.Start();
        btnPauseResume.Text = "暫停";
    }
}

2. 關閉前確認對話框

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();
        }
    }
}

3. 使用 async/await 替代 Timer(.NET 4.5+)

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() 導致不觸發 Tick
  • ❌ 使用 Thread.Sleep 阻塞 UI 線程,界面凍結
  • ❌ 在 Tick 中直接 Application.Exit() 而非 this.Close(),可能導致資源未正確釋放
  • ✅ 將 Timer 定義為類級字段,而非局部變量,防止被 GC 回收
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved