我需要的是让计时器触发事件处理程序(比如说每秒) 在另一堂课。这将是Windows窗体程序的一小部分。
我尝试使用委托来“调用”事件处理程序,但我一直在努力 语法错误。有人可以用简单的方法引导我走向正确的方向 代码示例?
下面的代码是我的开始,评论部分工作正常,但我想要 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
}
}
}
}
答案 0 :(得分:1)
另一个类是静态的吗? 以下是每个例子:
//Static class
Timer1.Tick += YourClass.DoStuff;
//Non-static class
YourClass MyInstance = new YourClass();
Timer1.Tick += MyInstance.DoStuff;
只需将代码放在表单的构造函数中即可。