動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
処理概要
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();
}
}
}
実行
ボタン押下後の様子。