简体   繁体   English

从类C#Windows窗体访问窗体控件

[英]Accessing a forms controls from a class c# windows forms

hi I have a timer control on my main form which creates an instance of a class, under certain conditions the class's method needs to stop the timer. 嗨,我在主窗体上有一个计时器控件,该控件创建一个类的实例,在某些情况下,该类的方法需要停止计时器。

is there a way to set the timers Enabled property to false without having passed the control in to the method? 有没有一种方法可以将计时器Enabled属性设置为false,而无需将控件传递给方法?

could I some how check all the controls on the mainform for the timer and then disable it? 我可以如何检查计时器主窗体上的所有控件,然后将其禁用?

I'd have the class have a constructor that either takes an interface 我要让该类具有一个采用接口的构造函数

interface IStopTimer
{
    void StopTimer();
}

class MyClass
{
    public MyClass(IStopTimer stopTimer)
    ...

or a delegate 或代表

class MyClass
{
    public MyClass(Action stopTimer)
    ...

Or possibly the timer method to achieve the same thing. 或者可能是计时器方法来实现相同的目的。 This way the class isn't dependent on Windows Forms, and has no idea what you're using for a timer. 这样,该类就不依赖于Windows Forms,也不知道您要使用的计时器是什么。

One way or another the method will need a reference (directly or indirectly) to the timer to stop it. 该方法将以一种或另一种方式(直接或间接)引用计时器以使其停止。 You can layer abstractions on it but it won't be pretty. 您可以在其上分层抽象,但效果并不理想。

Could you use something like ThreadPool.QueueUserWorkItem() instead of a timer to start the operation the timer carries out? 您可以使用ThreadPool.QueueUserWorkItem()类的东西代替计时器来启动计时器执行的操作吗? That way when the operation is complete the thread will go back to the pool and you have a "fire-and-forget" mechanism. 这样,当操作完成时,线程将返回到池中,并且您具有“即发即弃”机制。

You could create an event from the class that stops the timer and raise it whenver you want that to happen. 您可以从该类中创建一个事件,该事件将停止计时器,并在您希望发生该事件的任何时间引发它。 From the outer class (main form) after you instaciate the class you subscribe to that event and stop the timer in the handler. 在使该类实例化之后,从外部类(主窗体)开始,您订阅该事件并在处理程序中停止计时器。

This is how you raise the event: 这是引发事件的方式:

    class Class1
{
    public event EventHandler StopTimer;

    public void SomeMethod()
    {
        if (StopTimer != null)
            StopTimer(this, EventArgs.Empty);
    }

}

This is what you have in the main form: 这是您的主要形式:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Class1 myClass = new Class1();
        myClass.StopTimer += new EventHandler(myClass_StopTimer);

        timer1.Enabled = true;
        timer1.Start();
    }

    void myClass_StopTimer(object sender, EventArgs e)
    {
        timer1.Stop();
        timer1.Enabled = false;
    }
}

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

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