개발

[C#, WPF] 타이머 만들기

딱딱키보드 2024. 6. 8. 10:32
728x90
SMALL

요즘엔 웹서비스가 좋아서 개발이 많이 필요하지 않습니다. 타이머가 필요하면 구글에 검색만 해도 넘치게 나옵니다.

그러나 개발자라면 그 원리를 알고 만들 수 있어야 하지 않을까 하여 간단한 예제를 만들어봅니다.

기초적인 C#과 WPF를 이용하여 타이머를 디자인하고 기능을 연결하는것까지 연습해보았습니다.

 

이 타이머는 사용자가 시간(초 단위)을 설정하고, 시작, 일시 정지, 재시작, 리셋할 수 있는 기능을 포함합니다.

 

 

  • 새 WPF 프로젝트 생성:
    • Visual Studio를 열고, 새 프로젝트를 만듭니다.
    • 프로젝트 템플릿에서 "WPF App (.NET Core)"를 선택하고, 프로젝트 이름을 입력한 후 생성합니다.
  • XAML 코드 수정:
    • MainWindow.xaml 파일을 열고, 다음과 같은 XAML 코드를 작성합니다.
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Timer" Height="200" Width="300">
    <Grid>
        <Label Content="Set Timer (seconds):" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
        <TextBox Name="TimeInput" HorizontalAlignment="Left" Height="30" Margin="140,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Name="TimerLabel" Content="00:00:00" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36"/>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20">
            <Button Content="Start" Width="60" Margin="10" Click="StartButton_Click"/>
            <Button Content="Pause" Width="60" Margin="10" Click="PauseButton_Click"/>
            <Button Content="Reset" Width="60" Margin="10" Click="ResetButton_Click"/>
        </StackPanel>
    </Grid>
</Window>

 

 

C# 코드 수정:

  • MainWindow.xaml.cs 파일을 열고, 다음과 같은 코드를 작성합니다.
using System;
using System.Windows;
using System.Windows.Threading;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        private DispatcherTimer _timer;
        private TimeSpan _time;

        public MainWindow()
        {
            InitializeComponent();
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (_time.TotalSeconds > 0)
            {
                _time = _time.Add(TimeSpan.FromSeconds(-1));
                TimerLabel.Content = _time.ToString(@"hh\:mm\:ss");
            }
            else
            {
                _timer.Stop();
                MessageBox.Show("Time's up!");
            }
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            if (int.TryParse(TimeInput.Text, out int seconds))
            {
                _time = TimeSpan.FromSeconds(seconds);
                TimerLabel.Content = _time.ToString(@"hh\:mm\:ss");
                _timer.Start();
            }
            else
            {
                MessageBox.Show("Please enter a valid number of seconds.");
            }
        }

        private void PauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (_timer.IsEnabled)
            {
                _timer.Stop();
            }
            else
            {
                _timer.Start();
            }
        }

        private void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            _timer.Stop();
            _time = TimeSpan.Zero;
            TimerLabel.Content = "00:00:00";
            TimeInput.Text = "";
        }
    }
}

 

이 코드에서는 다음과 같은 기능을 구현합니다:

  • 사용자가 입력한 시간(초)을 설정하여 타이머를 시작합니다.
  • 타이머는 매 초마다 갱신되어 화면에 표시됩니다.
  • 타이머가 0이 되면 멈추고 알림 메시지를 표시합니다.
  • 일시 정지 및 재시작 기능을 제공합니다.
  • 타이머를 리셋할 수 있습니다.

 

이 예제를 통해 간단한 타이머 프로그램을 만들 수 있습니다. 필요에 따라 UI를 더 꾸미거나 기능을 추가할 수 있습니다.

728x90
LIST