程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> WPF制作一個簡單的倒計時器實例附源碼

WPF制作一個簡單的倒計時器實例附源碼

編輯:ASP.NET基礎
實例一
早上起來後閒的無事,於是想到前些日子學院的某個老師讓大家給他找個什麼倒計時的小軟件,當時大家忙於復習所以也懶得搭理這件事,囧~。既然早上沒事干,何不寫個玩玩~既然要寫,就用以前沒怎麼搗鼓過的WPF寫一個吧,也算是一次學習WPF的初探吧(感覺自己很落後了)!

在Vs2008和Vs2010之間徘徊了許久之後,最終還是選擇了Vs2008做開發IDE。在Vs2008中建了個WPF工程後,浏覽了下默認生成的工程文件結構,一個App.xaml(當然還有App.xaml.cs)和一個Windows1.xaml(Windows1.xaml.cs)。設計界面也和之前的Window Form程序大不一樣了,感覺和Flex差不多,不支持直接拖拽到指定位置的界面設計(在此感謝 cesium和 Muse為我指出問題所在),還真是有點不怎麼習慣哦~
好了,開始做個簡單的倒計時器了。 先讓大家看下運行效果吧,顯示在屏幕正中央且置頂顯示:
 
由於比較簡單,就三個文件便寫完了,分別為界面設計的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。

實例二
效果:
 
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--;
    }
  }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved