0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Visual Studio | WPF > タイマーイベント > ボタン押下からの経過秒数を取得する > DispatcherTimer + DateTime.Subtract()

Posted at
動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

処理概要

  • Buttonを押した時に1秒インターバルのタイマーを起動する
    • DispatcherTimer 使用
  • タイマーの処理ごとに経過秒数をDateTime.Subtract()で取得する

code

MainWindow.xaml
<Window x:Class="_171110_t1515_dispatcherTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_171110_t1515_dispatcherTimer"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <TextBlock Name="T_time" Height="50" Text=""/>
            <Button Width="120" Height="30" Content="Start" Click="Button_Click"/>
        </StackPanel>
    </Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//以下を追加 (DispatcherTimerのため)
using System.Windows.Threading;

namespace _171110_t1515_dispatcherTimer
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer myTimer;
        DateTime startTime;

        public MainWindow()
        {
            InitializeComponent();

            myTimer = new DispatcherTimer(DispatcherPriority.Normal);
            myTimer.Interval = new TimeSpan(0, 0, 1);
            myTimer.Tick += myTimer_Tick;
        }

        void myTimer_Tick(object sender, EventArgs e)
        {
            int elapsed_sec = DateTime.Now.Subtract(startTime).Seconds;
            T_time.Text = elapsed_sec.ToString() + " sec";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            startTime = DateTime.Now;
            myTimer.Start();
        }
    }
}

実行

ボタン押下後の様子。

qiita.png

関連

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?