定時器使用的程序。開始---》不斷輸入aaa 可以停止 繼續。
引用:using System.Timers; //、、、、、、、、、、、、、、 public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Load += Form1_Load; } //新建定時器。要用System.Timers.Timer。 //不要用forms.Timer的定時器。這個不精準 System.Timers.Timer myTimer; void Form1_Load(object sender, EventArgs e) { myTimer =new System.Timers.Timer(2000);//定時週期2秒 myTimer.Elapsed += myTimer_Elapsed;//到2秒了做的事件 myTimer.AutoReset = true; //是否不斷重複定時器操作 } void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { richTextBox1.Text = richTextBox1.Text + "\n" + "aaa"; } //開始按鈕 private void button1_Click(object sender, EventArgs e) { myTimer.Enabled = true; //定時器開始用 //如果不寫下面這句會有一個異常。 //異常:線程間操作無效: 從不是創建控件"richtextbox"的線程訪問它 //但這不是最好的方法。如果只有一個進程調用richtextbox而已。就可以用下面這句 //如果有多個線程調用richtextbox等控件。就要用委託。具體百度 //一篇參考博客http://www.cnblogs.com/zyh-nhy/archive/2008/01/28/1056194.html Control.CheckForIllegalCrossThreadCalls = false; } private void button2_Click(object sender, EventArgs e) { if (myTimer.Enabled) { myTimer.Enabled = false; //定時器停止 button2.Text = "continue"; } else { myTimer.Enabled = true; button2.Text = "pause"; } } private void button3_Click(object sender, EventArgs e) { myTimer.Close(); //釋放Timer佔用的資源 myTimer.Dispose(); richTextBox1.Text = richTextBox1.Text + "\n" + "over"; } }