C#倒數計時器範例教學

本篇文章分享如何使用C#來製作簡易的倒數計時器並提供範例教學,倒數計時器主要藉由Windows Form的Timer元件來實現,藉由判斷label上數字扣除到0的時候即執行需要計時的功能。

C#倒數計時器範例教學

  倒數計時器範例  

第一步驟 建立C#的Timer物件

C#倒數計時器範例教學

第二步驟建立顯示視窗UI元件

備註:這邊主要建立兩個label元件分別為 label1 與 label2

C#倒數計時器範例教學

第三步驟:設定Timer物件參數

將timer的 Interval 參數設定為 1000,代表每1秒執行一次。

C#倒數計時器範例教學

第四步驟:倒數計時器程式碼撰寫(以下提供倒數5秒的C#範例)

C#程式碼範例講解:

1.首先需要將Timer【timer1.Start】 啟動

2. int timeLeft = 5; 設定秒數為5秒,每一秒就執行減一,等到數字歸零即表示倒數時間已到。

3.C#程式範例如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Timer
{
    public partial class Form1 : Form
    {
        int timeLeft;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            timeLeft = 5;
            label2.Text = "5 seconds";
            /* Timer 啟動 */
            timer1.Start();
        }
 
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (timeLeft > 0)
            {
                timeLeft = timeLeft - 1;
                label2.Text = timeLeft + " seconds";
            }
            else
            {
                /* 倒數時間到執行 */
 
                timeLeft = 5;
                label2.Text = "5 seconds";
            }
        }
    }
}

延伸閱讀:

C#讀取XML檔案內容資訊

C#資料庫語法新增與刪除

C# TextBox文字自定義顏色

C# MessageBox 教學

C#讀取Excel檔案的操作教學&程式碼範例