2013-10-07 32 views
1

我需要的是讓一個計時器觸發一個事件處理程序(比如說每秒),其中一個 在另一個類中。這將是Windows窗體程序的一小部分。一個計時器對象的C#事件處理程序

我曾嘗試使用委託「調用」事件處理程序,但我不斷收到 語法錯誤。有人可以用一個簡單的 代碼示例指引我正確的方向嗎?

下面的代碼是我的開始,評論部分工作正常,但我想在Windows定時器觸發時觸發 事件。

namespace WindowsFormsApplication3 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public event TimerHandler Tick; 
     public EventArgs e = null; 
     public delegate void TimerHandler(Timer t, EventArgs e); 

     public class Timer 
     { 
      public event TimerHandler Tick; 
      public EventArgs e = null; 
      public delegate void TimerHandler(Timer t, EventArgs e); 
     } 

     public class Listener 
     { 
      public static int ticker = 0; 
      public void Subscribe(Timer t) 
      { 
       t.Tick += new Timer.TimerHandler(HeardTick); 
      } 
      private void HeardTick(Timer t, EventArgs e) 
      { 
       //lblTimer.Text = ticker.ToString(); //Don't know how to change forms control 
       ticker++; 
      } 
     } 

     private void btnStart_Click_1(object sender, EventArgs e) 
     { 
      Timer t = new Timer(); 
      Listener l = new Listener(); 
      l.Subscribe(t); 
      //t.Start(); 
     } 

     public void timer1_Tick(object sender, EventArgs e) 
     { 
      if (Tick != null) 
      { 
       Tick(this, e); // "this" is incorrect, invalid argument 
      } 
     } 
    } 
} 
+2

向我們顯示您的代碼!我們將幫助您糾正它。 – Anirudha

+2

** Close-Voting:** *詢問代碼的問題必須證明對所解決問題的最小理解。包括嘗試的解決方案,爲什麼他們不工作,以及預期的結果。* –

+0

也許讓新手有機會在結束之前編輯他的問題? :) –

回答

1

其他類是靜態的嗎? 下面是每個一個例子:

//Static class 
Timer1.Tick += YourClass.DoStuff; 

//Non-static class 
YourClass MyInstance = new YourClass(); 
Timer1.Tick += MyInstance.DoStuff; 

只要把代碼在窗體的構造函數。