using System;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private DispatcherTimer timer;
private ProcessCount processCount;
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWin_Loaded);
}
/// <summary>
/// 窗口加载事件
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void MainWin_Loaded(object sender, RoutedEventArgs e)
{
//设置定时器
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(10000000); //时间间隔为一秒
timer.Tick += new EventHandler(timer_Tick);
}
/// <summary>
/// Timer触发的事件
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void timer_Tick(object sender, EventArgs e)
{
if (OnCountDown())
{
TimeTextBlock.Text =processCount.GetHour() +”:”+ processCount.GetMinute() + “:” + processCount.GetSecond();
}
else
timer.Stop();
}
/// <summary>
/// 处理事件
/// </summary>
public event CountDownHandler CountDown;
public bool OnCountDown()
{
if (CountDown != null)
return CountDown();
return false;
}
/// <summary>
/// 处理倒计时的委托
/// </summary>
/// <returns></returns>
public delegate bool CountDownHandler();
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//转换成秒数
Int32 hour = Convert.ToInt32(HourArea.Text);
Int32 minute = Convert.ToInt32(MinuteArea.Text);
Int32 second = Convert.ToInt32(SecondArea.Text);
//处理倒计时的类
processCount = new ProcessCount(hour * 3600 + minute * 60 + second);
CountDown += new CountDownHandler(processCount.ProcessCountDown);
//开启定时器
timer.Start();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfApplication1
{
/// <summary>
/// 实现倒计时功能的类
/// </summary>
public class ProcessCount
{
private Int32 _TotalSecond;
public Int32 TotalSecond
{
get { return _TotalSecond; }
set { _TotalSecond = value; }
}
/// <summary>
/// 构造函数
/// </summary>
public ProcessCount(Int32 totalSecond)
{
this._TotalSecond = totalSecond;
}
/// <summary>
/// 减秒
/// </summary>
/// <returns></returns>
public bool ProcessCountDown()
{
if (_TotalSecond == 0)
return false;
else
{
_TotalSecond–;
return true;
}
}
/// <summary>
/// 加秒
/// </summary>
/// <returns></returns>
public bool ProcessCountUp()
{
_TotalSecond++;
return true;
}
/// <summary>
/// 获取小时显示值
/// </summary>
/// <returns></returns>
public string GetHour()
{
return String.Format(“{0:D2}”, (_TotalSecond/3600));
}
/// <summary>
/// 获取分钟显示值
/// </summary>
/// <returns></returns>
public string GetMinute()
{
return String.Format(“{0:D2}”, (_TotalSecond%3600)/60);
}
/// <summary>
/// 获取秒显示值
/// </summary>
/// <returns></returns>
public string GetSecond()
{
return String.Format(“{0:D2}”, _TotalSecond%60);
}
}
}