WPF制作一个简单的倒计时器实例附源码

御风而行 2012-12-27

实例一
早上起来后闲的无事,于是想到前些日子学院的某个老师让大家给他找个什么倒计时的小软件,当时大家忙于复习所以也懒得搭理这件事,~。既然早上没事干,何不写个玩玩~既然要写,就用以前没怎么捣鼓过的WPF写一个吧,也算是一次学习WPF的初探吧(感觉自己很落后了)!

在Vs2008和Vs2010之间徘徊了许久之后,最终还是选择了Vs2008做开发IDE。在Vs2008中建了个WPF工程后,浏览了下默认生成的工程文件结构,一个App.xaml(当然还有App.xaml.cs)和一个Windows1.xaml(Windows1.xaml.cs)。设计界面也和之前的Window Form程序大不一样了,感觉和Flex差不多,不支持直接拖拽到指定位置的界面设计(在此感谢 cesium和 Muse为我指出问题所在),还真是有点不怎么习惯哦~
好了,开始做个简单的倒计时器了。 先让大家看下运行效果吧,显示在屏幕正中央且置顶显示:
WPF制作一个简单的倒计时器实例附源码 
由于比较简单,就三个文件便写完了,分别为界面设计的MainWin.xaml和应用程序类App.xaml 和倒计时处理类ProcessCount.cs类文件。代码分别如下:
倒计时处理类ProcessCount.cs :

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
namespace CountDown 
{ 
/// <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 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); 
} 
} 
}

窗口界面设计文件MainWin.xaml

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 <Window x:Class="CountDown.MainWin" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="400" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" 
Title=" " Topmost="True" WindowStyle="None" Background="Transparent" AllowsTransparency="True" WindowStartupLocation="CenterScreen"> 
<Grid> 
<Grid.ColumnDefinitions> 
<ColumnDefinition /> 
<ColumnDefinition Width="40"/> 
<ColumnDefinition /> 
<ColumnDefinition Width="40"/> 
<ColumnDefinition /> 
</Grid.ColumnDefinitions> 
<TextBlock Text="00" Name="HourArea" VerticalAlignment="Center" FontSize="180" Background="Red" Grid.Column="0"/> 
<TextBlock Text=":" Name="HourSplitMinute" VerticalAlignment="Center" FontSize="180" Background="Red" Grid.Column="1"/> 
<TextBlock Text="10" Name="MinuteArea" VerticalAlignment="Center" FontSize="180" Background="Red" Grid.Column="2" /> 
<TextBlock Text=":" Name="MinuteSplitSecond" VerticalAlignment="Center" FontSize="180" Background="Red" Grid.Column="3"/> 
<TextBlock Text="00" Name="SecondArea" VerticalAlignment="Center" FontSize="180" Background="Red" Grid.Column="4"/> 
</Grid> 
</Window>

窗口界面逻辑设计文件:MainWin.xaml.cs:

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
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.Shapes; 
using System.Windows.Threading; 
namespace CountDown 
{ 
/// <summary> 
/// Interaction logic for MainWin.xaml 
/// </summary> 
public partial class MainWin : Window 
{ 
private DispatcherTimer timer; 
private ProcessCount processCount; 
public MainWin() 
{ 
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); 
//转换成秒数 
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(); 
} 
/// <summary> 
/// Timer触发的事件 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
private void timer_Tick(object sender, EventArgs e) 
{ 
if (OnCountDown()) 
{ 
HourArea.Text = processCount.GetHour(); 
MinuteArea.Text = processCount.GetMinute(); 
SecondArea.Text = 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(); 
}

鉴于代码中注释的比较详细,所以笔者也不再一一赘述了,希望对大家能有所帮助。完整的工程包下载:http://xiazai.jb51.net/201212/yuanma/CountDown_jb51.rar。

实例二
效果:
WPF制作一个简单的倒计时器实例附源码 
UI:放置一个Label ---><Label name="lblSecond" FontSize="20" Foreground="Red" ></Label>
CS:

代码如下:

  private int countSecond=300; //记录秒数 
  private void UserControl_Loaded(object sender, RoutedEventArgs e) 
  { 
    private DispatcherTimer disTimer = new DispatcherTimer(); 
    disTimer.Interval = new TimeSpan(0, 0, 0, 1); //参数分别为:天,小时,分,秒。此方法有重载,可根据实际情况调用。 
    disTimer.Tick += new EventHandler(disTimer_Tick); //每一秒执行的方法 
    disTimer.Start(); 
  } 
  void disTimer_Tick(object sender, EventArgs e) 
  { 
    if(countSecond==0) 
    { 
      MessageBox.Show("结束"); 
    } 
    else 
    { 
      //判断lblSecond是否处于UI线程上 
      if (lblSecond.Dispatcher.CheckAccess()) 
      { 
        lblSecond.Content=countSecnd.ToString(); 
      } 
      else 
      { 
        lblSecond.Dispatcher.BeginInvoke(DispatcherPriority.Normal,(Action)(() =>{ 
          lblSecond.Content=countSecond.ToString(); 
        }));   
      } 
      countSecond--; 
    } 
  }

相关推荐