C#如何引发事件以从主窗体以外的类启动计时器?

时间:2016-09-16 15:43:11

标签: c# winforms events timer void

在我的主Form1中,我有

int duration = 5;
public void timer1_Tick(object sender, EventArgs e)
{
    duration--;
    if (duration == 0)
    {
       timer1.Stop();
       MessageBox.Show("timesup");
    }
}

在其他地方(特别是我用于我的UDP侦听器的类),我运行一个事件来引用对表单的更改

private MyProject.Form1 _form { get; set; }
public UDPListener(TapeReader.Form1 form)
{
     _form = form;
}

然后,当输入数据符合我的标准时,我会尝试调用它

if (numberSize>paramSize)
{
    if (_form.listBox1.InvokeRequired)
    {
          _form.listBox1.Invoke((MethodInvoker)delegate ()
          {
              //Below is where I would like the timer to start
              _form.timer1.Start();   
              //This won't work as I need the timer1_Tick from the main. How can I run this from a different class other than the main form?
          });
    }
}

与我的表单的其他组件一样,我可以使用_form引用它,但timer1_Tick是一个方法(void)。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

想出一个解决方案。我刚刚使用本教程来帮助我https://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick(v=vs.110).aspx

在我的另一堂课中,我有:

 _form.timer1.Tick += new EventHandler(TimerEventProcessor);

我将它引用到

int duration = 5;
    private void TimerEventProcessor(object myObject, EventArgs myEventArgs)
    {
        duration--;
        if(duration==0)
        {
            MessageBox.Show("timesup");

        }
    }