C# のカウントダウンタイマー

Muhammad Maisam Abbas 2021年5月23日 2021年5月9日
C# のカウントダウンタイマー

このチュートリアルでは、C# でカウントダウンタイマーを作成する方法について説明します。

C# のタイマークラスでタイマーをカウントダウン

タイマークラス)は、C# の別のスレッド内で関数を実行するために使用されます。タイマー関数を使用して、C# でカウントダウンタイマーを作成できます。Timer.Interval プロパティは、タイマーの各ティック間の間隔をミリ秒単位で設定します。Timer.Tick プロパティは、各ティックで特定のタスクを実行します。合計時間をデクリメントして、合計時間がゼロになるまで、ティックごとにユーザーに表示できます。次のコード例は、C# で Timer クラスを使用してカウントダウンタイマーを作成する方法を示しています。

using System;
using System.Windows.Forms;

namespace countdown_timer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private int duration = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(count_down);
            timer1.Interval = 1000;
            timer1.Start();

        }
        private void count_down(object sender, EventArgs e)
        {
            
            if (duration == 0)
            {
                timer1.Stop();

            }
            else if(duration > 0)
            {
                duration--;
                label1.Text = duration.ToString();
            }
        }
    }
}

出力:

C# カウントダウンタイマー

上記のコードで、C# の Timer クラスを使用して 60 秒から 0 秒までカウントするカウントダウンタイマーを作成しました。Timer.Interval を 1 秒に等しい 1000 ミリ秒に等しく設定し、値が 0 に等しくなるまで、ティックごとにユーザーに表示される値をデクリメントしました。タイマーは Timer.Start() 関数で開始し、最後に duration0 に等しくなると、C# の Timer.Stop() 関数でタイマーを停止しました。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

関連記事 - Csharp Timer