C# x Timer x 定時執行
Form裡面要有 :
Button *1
TextBox1 *1
/////////////////////以下 程式碼/////////////////////
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication31
{
public partial class Form1 : Form
{
System.Timers.Timer testTimer;
int intNum;
public Form1()
{
InitializeComponent();
}
public void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TextBox1.Text = TextBox1.Text + "\n\n" + intNum.ToString() ;
intNum = intNum + 1;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Star")
{
testTimer = new System.Timers.Timer(2000);//定時週期2秒
testTimer.Elapsed += myTimer_Elapsed;//每兩秒做這件事
testTimer.AutoReset = true; //是否不斷重複定時器操作
testTimer.Enabled = true; //定時器啟動
Control.CheckForIllegalCrossThreadCalls = false;
button1.Text = "Stop";
}
else
{
testTimer.Close();
testTimer.Dispose();
TextBox1.Text = TextBox1.Text + "\n\n" + "Stop";
button1.Text = "Star";
}
}
}
}
/////////////////////以上 程式碼/////////////////////
執行畫面
參考資料 : http://blog.csdn.net/kankankankan2222/article/details/8249602