我們平時在C#中要用到定時功能時,有自帶定時器,一般在定時器里面寫函數就行了,現在需要在類里面寫了一個定時器,不和界面綁定,一開始的時候感覺沒什么思路,然后看了一下界面的設計代碼,有了思路,還是很簡單的
首先我們在界面上放一個定時器,看一下代碼:
this.timer1 = new System.Windows.Forms.Timer(this.components); this.timer1.Enabled = true; this.timer1.Interval = 2000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
我們用Timer類創建timer1這個實例,調用它的方法就好了,修改代碼如下:
public partial class Form1 : Form { private int i = 0; public Form1() { InitializeComponent(); Timer timer1 = new Timer(); timer1.Enabled = true; timer1.Interval = 1000; timer1.Tick += new System.EventHandler(this.timer1_Tick); } private void timer1_Tick(object sender, EventArgs e) { i++; textBox1.Text += i + "S" + "\r\n"; } }
效果如圖所示:
有時候我們還會遇到另外一種情況,需要程序延時運行,尤其是像我做攝像頭,需要攝像頭在一個地方停留一段時間再繼續運行的,使用上面的定時器方法是不行的,我在網上搜索了一個方法,很管用:
public static bool Delay(int delayTime) { DateTime now = DateTime.Now; int s; do { TimeSpan spand = DateTime.Now - now; s = spand.Seconds; Application.DoEvents(); } while (s < delayTime); return true; }
寫一個循環驗證一下:
public void hh() { for (int i = 0; i < 5; i++) { textBox1.Text += "抓圖" + i + "\r\n"; if(Delay(5)) { continue; } } }
完美解決