最近作一個WPF小項目須要使用到計時器,所以寫了一個計時控件,記錄下來,以便下次使用。express
前臺的XAML:服務器
<UserControl x:Class="Test.CountDown" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="110" d:DesignWidth="150"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="43*" /> <ColumnDefinition Width="13"/> <ColumnDefinition Width="43*" /> <ColumnDefinition Width="13"/> <ColumnDefinition Width="43*" /> </Grid.ColumnDefinitions> <TextBlock Text="00" Name="HourArea" VerticalAlignment="Center" FontSize="30" Background="Transparent" Grid.Column="0" Foreground="DarkOrange" /> <TextBlock Text=":" Name="HourSplitMinute" VerticalAlignment="Center" FontSize="30" Background="Transparent" Grid.Column="1" Foreground="DarkOrange" /> <TextBlock Text="00" Name="MinuteArea" VerticalAlignment="Center" FontSize="30" Background="Transparent" Grid.Column="2" Foreground="DarkOrange" /> <TextBlock Text=":" Name="MinuteSplitSecond" VerticalAlignment="Center" FontSize="30" Background="Transparent" Grid.Column="3" Foreground="DarkOrange" /> <TextBlock Text="00" Name="SecondArea" VerticalAlignment="Center" FontSize="30" Background="Transparent" Grid.Column="4" Foreground="DarkOrange" /> </Grid> </UserControl>
後臺的邏輯:ide
public partial class CountDown : UserControl { public DispatcherTimer timer; public Process pro; public Stopwatch sw = new Stopwatch(); public int seconds; public CountDown() { InitializeComponent(); pro = new Process(); timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += new EventHandler(timer_Tick); } void timer_Tick(object sender, EventArgs e) { TimeSpan ts = new TimeSpan (0,0,seconds); pro.totalSecond = (int)(ts - sw.Elapsed).TotalSeconds; if (pro .totalSecond > 0) { HourArea.Text = pro.GetHour(); MinuteArea.Text = pro.GetMinute(); SecondArea.Text = pro.GetSecond(); } else { timer.Stop(); sw.Stop (); sw.Reset(); SecondArea.Text = string.Format("{0:D2}", 0); } } } public class Process { public int totalSecond; //獲取小時字符串 public string GetHour() { return string.Format("{0:D2}", totalSecond / 3600); } //獲取分鐘字符串 public string GetMinute() { return string.Format("{0:D2}", (totalSecond / 60 - ((int)(totalSecond / 3600) * 60))); } //獲取秒字符串 public string GetSecond() { return string.Format("{0:D2}", totalSecond % 60); } }
調用:this
this.countDown1.timer.Stop();
this.countDown1.sw.Reset();
this.countDown1.seconds = 300;//傳入倒計時總時間(秒)
this.countDown1.timer.Start();
this.countDown1.sw.Start();
2014。11.28日補充:spa
最近一個小項目須要用到服務器的系統時間,並且須要精確到小數點後三位。方法以下:pwa
public DateTime GetTime() { string strSql = "select getdate()"; DateTime dt; SqlDataReader dataReader = DbHelperSQL.ExecuteReader(strSql); if (dataReader.Read()) { dt = (DateTime)dataReader[0]; dataReader.Close(); return dt; } return DateTime.MinValue; }