WPFでカウントダウン
今回はWPFでタイマーを使用してカウントダウンするプログラム制作にポンコツ2人組が挑戦してみました。 開発環境はVisualStudio2019を使用しました。
MainWindow.xaml
Window内に1つのGridがあり、その中にTextBlock要素が配置されています。
このTextBlock要素はカウントダウンの残り秒数を表示するために使われます。
<Window x:Class="TimerExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Timer Example" Height="200" Width="300">
<Grid>
<TextBlock x:Name="countdownText" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24" Text="30"/>
</Grid>
</Window>
MainWindow.xaml.cs
コンストラクタ内で、System.Windows.Threading.DispatcherTimerオブジェクトであるtimerが初期化されます。
30から1秒ごとにカウントダウンしていき、0以下になったら"終了"と表示します。
また、アプリケーション終了時にはタイマーを停止してリソースを解放します。
using System;
using System.Threading.Tasks;
using System.Windows;
namespace TimerExample
{
public partial class MainWindow : Window
{
private int countdownSeconds = 30;
private System.Windows.Threading.DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
// タイマーの初期化
timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1); // 1秒ごとに更新
timer.Tick += TimerTick;
// タイマーを開始
timer.Start();
}
private void TimerTick(object sender, EventArgs e)
{
countdownSeconds--;
if (countdownSeconds >= 0)
{
// 残り秒数を画面に表示
countdownText.Text = countdownSeconds.ToString();
}
else
{
// カウントダウン終了時の処理
timer.Stop();
countdownText.Text = "終了";
}
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// アプリケーション終了時にタイマーを停止してリソースを解放
timer.Stop();
timer.Tick -= TimerTick;
timer = null;
}
}
}
以下がアプリケーションを実行した画面です。無事カウントダウンされました!