C# Timer範例教程

這是一個關於Timer的例子,我們將創建一個簡單的應用程序,使用Timer對象來倒計時一個由自己設定的時間並循環播放一段音樂,直到重設Timer控件。
Timer對象基礎
首先你要知道的是,使用Timer對象你需要訪問如下命名空間:

using System.Threading;
using System.Timers;

接下來,介紹一下創建一個Timer的要點以及爲這個timer對象的Elapsed事件設定事件委派。
先創建一個Timer對象,這裏定義使用的timer爲timerClock。接下來設定Elapsed事件委派,當事件被觸發時,指定的委派將被調用,這裏定義使用的委派名稱爲OnTimer()。
接着,設定Interval屬性,使用毫秒數值指示希望Elapsed事件被調用的間隔,這意味着,當定義Interval屬性爲1000毫秒時,定義的委派OnTimer()將每隔1000毫秒被調用一次,或者說是每隔1秒。
最後,需要設定Enabled屬性爲true,以使這個timer對象開始工作。接下來,剩下的只是一個小問題—創建一個委派,在這個timer對象的Elapsed屬性被觸發時調用。如果以前沒有使用過委派,不用擔心,它們很容易使用,只需要創建一個方法,用來接收適合你捕獲事件的一些變量。
針對Elapsed事件,這個委派需要接收一個普通對象和一個ElapsedEventArgs對象。

private System.Timers.Timer timerClock = new System.Timers.Timer();
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
public void OnTimer( Object source, ElapsedEventArgs e )
{
//Your code here
}
在報警程序中使用Timer控件
介紹了這些基礎,現在來看在實際應用中的代碼。注意,這裏並不包括播放音樂和顯示最小化圖標的代碼。
在下面的代碼中,可以看到,將實例化Timer對象的方法放在初始化方法InitializeTimer()中,這個方法將被類構造調用。並且創建了兩個方法,inputToSeconds()和secondsToTime()用來將字符串格式的時間格式轉換爲正型,以及一個反處理過程。這些方法只是用來幫助我們在TextBox控件中顯示日期格式,這在整個應用的結構中,並不十分重要。其他的那些代碼,是標準的Visual Studio.NET爲Win Form程序生成的樣板文件。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Timers;
using System.IO;
using System.Reflection;
namespace timerAlarm
{
public class TimerForm : System.Windows.Forms.Form
{
//Controls and Components
private System.Windows.Forms.TextBox timerInput;
private System.Windows.Forms.Button StartButton;
private System.Windows.Forms.Button ResetButton;
private System.ComponentModel.IContainer components;
//Timer and associated variables
private System.Timers.Timer timerClock = new System.Timers.Timer();
private int clockTime = 0;
private int alarmTime = 0;
public TimerForm()
{
InitializeComponent();
InitializeTimer();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
#endregion
public void InitializeTimer()
{
this.timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
this.timerClock.Interval = 1000;
this.timerClock.Enabled = true;
}
[STAThread]
static void Main()
{
Application.Run(new TimerForm());
}
private void TimerForm_Resized(object sender, System.EventArgs e)
{
if( this.WindowState == FormWindowState.Minimized )
{
this.Hide();
}
}
private void StartButton_Click(object sender, System.EventArgs e)
{
this.clockTime = 0;
inputToSeconds( this.timerInput.Text );
}
private void ResetButton_Click(object sender, System.EventArgs e)
{
try
{
this.clockTime = 0;
this.alarmTime = 0;
this.timerInput.Text = "00:00:00";
}
catch( Exception ex )
{
MessageBox.Show("ResetButton_Click(): " + ex.Message );
}
}
public void OnTimer(Object source, ElapsedEventArgs e)
{
try
{
this.clockTime++;
int countdown = this.alarmTime - this.clockTime ;
if( this.alarmTime != 0 )
{
this.timerInput.Text = secondsToTime(countdown);
}
//Sound Alarm
if( this.clockTime == this.alarmTime )
{
MessageBox.Show("Play Sound");
}
}
catch( Exception ex )
{
MessageBox.Show("OnTimer(): " + ex.Message );
}
}
private void inputToSeconds( string timerInput )
{
try
{
string[] timeArray = new string[3];
int minutes = 0;
int hours = 0;
int seconds = 0;
int occurence = 0;
int length = 0;
occurence = timerInput.LastIndexOf(":");
length = timerInput.Length;
//Check for invalid input
if( occurence == -1 || length != 8 )
{
MessageBox.Show("Invalid Time Format.");
ResetButton_Click( null, null );
}
else
{
timeArray = timerInput.Split(’:’);
seconds = Convert.ToInt32( timeArray[2] );
minutes = Convert.ToInt32( timeArray[1] );
hours = Convert.ToInt32( timeArray[0] );
this.alarmTime += seconds;
this.alarmTime += minutes*60;
this.alarmTime += (hours*60)*60;
}
}
catch( Exception e )
{
MessageBox.Show("inputToSeconds(): " + e.Message );
}
}
public string secondsToTime( int seconds )
{
int minutes = 0;
int hours = 0;
while( seconds >= 60 )
{
minutes += 1;
seconds -= 60;
}
while( minutes >= 60 )
{
hours += 1;
minutes -= 60;
}
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
string strSeconds = seconds.ToString();
if( strHours.Length < 2 )
strHours = "0" + strHours;
if( strMinutes.Length < 2 )
strMinutes = "0" + strMinutes;
if( strSeconds.Length < 2 )
strSeconds = "0" + strSeconds;
return strHours + ":" + strMinutes + ":" + strSeconds;
}
}
}
實際的執行代碼比上面的要多,本範例演示了Timer在實際環境中的一個簡單應用,僅僅使用了一些簡單的基礎知識來創建一個簡單的應用。



.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章