timer计时 wpf_WPF计时器

using System;

using System.Windows;

using System.Windows.Threading;

namespace WpfStopWatch

{

///

/// MainWindow.xaml 的交互逻辑

///

public partial class MainWindow : Window

{

///

/// 状态

///

enum State

{

Start,

Pause,

End

}

///

/// 状态

///

State _state = State.End;

///

/// 计时用

///

TimeSpan _timeSpan = new TimeSpan(0,0,0,0,0);

public MainWindow()

{

InitializeComponent();

var t = new DispatcherTimer();

t.Interval = new TimeSpan(0,0,0,1);

t.Tick += OnTimer;

t.IsEnabled = true;

t.Start();

}

///

/// 时钟回调

///

///

///

void OnTimer(object sender, EventArgs e)

{

switch (_state)

{

case State.Start:

{

_timeSpan += new TimeSpan(0,0,0,1);

}break;

case State.Pause:

{

}

break;

case State.End:

{

_timeSpan = new TimeSpan();

//_timeSpan = new TimeSpan(0, 23, 12, 45, 54);

}

break;

}

var time = string.Format("{0:D2}:{1:D2}:{2:D2}", _timeSpan.Hours, _timeSpan.Minutes, _timeSpan.Seconds);

textBox1.Text = time;

}

///

/// 退出

///

///

///

private void button4_Click(object sender, RoutedEventArgs e)

{

Close();

}

///

/// 开始

///

///

///

private void button1_Click(object sender, RoutedEventArgs e)

{

_state = State.Start;

}

///

/// 暂停

///

///

///

private void button2_Click(object sender, RoutedEventArgs e)

{

_state = State.Pause;

}

///

/// 停止

///

///

///

private void button3_Click(object sender, RoutedEventArgs e)

{

_state = State.End;

}

}

}

你可能感兴趣的:(timer计时,wpf)