简体   繁体   English

如何从C#中的另一个类访问计时器

[英]How to access a timer from another class in C#

See Also: How to enable a timer from a different thread/class 另请参见: 如何从其他线程/类启用计时器

The timer is assigned to a form and I'd like to Enable it at a specific location,but from another class. 计时器已分配给表单,我想在其他位置的特定位置启用它。 I don't want to make it public 我不想公开

This is the code I use to access memo 这是我用来访问备忘录的代码

    public string TextValue
    {
        set
        {
            if (this.Memo.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    this.Memo.Text += value + "\n";
                });
            }
            else
            {
                this.Memo.Text += value + "\n";
            }
        }
    }

    public static void addtxt(string txt)
    {
        var form = Form.ActiveForm as Form1;
        if(form != null)
            form.TextValue = txt;
    }

If you don't want to expose the timer itself, expose a public method or property that you can call to enable the timer. 如果您不想公开计时器本身,请公开可调用以启用计时器的public方法或属性。 Obviously the Form that enables the Timer will need a reference to the Form that owns the Timer . 显然,启用计时器的Form将需要引用拥有TimerForm

How would you like to enable the timer ? 您想如何启用计时器? What action is undertaken in order to enable it ? 为了实现它采取了什么行动?

Is it possible to add an event to the class from which you want to enable the timer, and, on the form which contains the timer, subscribe to that event ? 是否可以在要启用计时器的类中添加事件,并在包含计时器的表单上订阅该事件? In the event-handler for that event, you can then enable the timer. 然后,在该事件的事件处理程序中,可以启用计时器。

When the other class raises the event, the eventhandler will enable the timer. 当另一个类引发事件时,事件处理程序将启用计时器。

public class SomeOtherClassThatDoesStuff
{
   public event EventHandler SomethingHappened;

   public void DoStuff()
   {
      ...
      if( SomethingHappened != null )
         SomethingHappened;
      ...
   }
}

public class Form1
{

    private void Button1_Click(object sender, EventArgs e )
    {

      SomeOtherClassThatDoesStuff o = new SomeOtherClassThatDoesStuff();
      o.SomethingHappened += new EventHandler(EnableTimer);

      o.DoStuff();
    }

    private void EnableTimer(object sender, EventArgs e )
    {
       myTimer.Enabled = true;
    }
}

Something like this. 这样的事情。 (I haven't tested, nor did I even compile it, but I think you'll catch the drift :) ). (我没有测试过,甚至也没有编译它,但是我认为您会发现其中的漂移:))。

将计时器设置为“内部”,则程序集中的其他类均可使用它。

You could add an accessor method to Enable the timer, this would allow yu to keep the timer private but make the method public, would that work? 您可以添加一个访问器方法来启用计时器,这将使yu保持计时器私有,但将方法设为公开,行之有效吗?

Also, you could look at making the accessor protected or internal , depending on who is calling it it may not need to be public. 另外,您可以考虑将访问器设置为protectedinternal ,这取决于谁称呼它,它可能不需要公开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM