Adrian
Adrian

Reputation: 1149

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?

could I some how check all the controls on the mainform for the timer and then disable it?

Upvotes: 0

Views: 361

Answers (3)

Liviu Mandras
Liviu Mandras

Reputation: 6607

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;
    }
}

Upvotes: 0

Neil Barnwell
Neil Barnwell

Reputation: 42095

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? That way when the operation is complete the thread will go back to the pool and you have a "fire-and-forget" mechanism.

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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.

Upvotes: 1

Related Questions