user3692208
user3692208

Reputation: 39

Disable timer from another form in c#

Hello I am following this post Control timer in form 1 from form 2, C# , response, the problem is that I can not solve it yet, I have a timer on form1, and I need to stop it from form2 try all that I found in this post but still nothing.

Form1

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

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();

        timer1.Enabled = true;

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        richTextBox1.AppendText("test\n");
    }
}

Form2

public partial class Form2 : Form
{

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        //
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 form1 = new Form1();
        form1.Hide();
        form1.timer1.Enabled = false;

    }
}

anyone can help me ?

Update :

static class Program
{

    /// <summary>
    /// Punto de entrada principal para la aplicación.
    /// </summary>
    [STAThread]
    public static Form1 MainForm;
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

Upvotes: 0

Views: 3900

Answers (1)

CodingGorilla
CodingGorilla

Reputation: 19862

The problem is that you are creating a new instance of Form1, so that is a different timer than the instance of the form you are looking at. You need to store a reference to the Form1 that is displayed (probably in your Program.Main).

So your Program.Main probably looks like this:

static class Program
{

    public static int Main()
    {
        Form1 form = new Form1();
        Application.Run(form);
    }
}

You want to store that reference, so modify it as such:

static class Program
{
    public static Form1 MainForm;

    [STAThread]
    public static int Main()
    {
        MainForm = new Form1(); // THIS IS IMPORTANT
        Application.Run(MainForm);
    }
}

And then you can use that stored referene in your Form2:

private void button1_Click(object sender, EventArgs e)
{
    Program.MainForm.Hide();
    Program.MainForm.timer1.Enabled = false;

}

This is a functional solution - personally I would not consider this an optimal solution. I would look at using something along the lines of an Event Aggregator/Broker, but if this is a really simple program without a lot of need for complexity, then this works.

Make sure the timer you need to access is modified as public, because the default modifier will be private.

Use the Properties panel provided by your IDE or use the designer code.

public System.Windows.Forms.Timer timer2;

change modifier to public

Upvotes: 3

Related Questions