3
votes

I have a context app that creates new Form to show some info to the user. This user can close the form using a button for that purpose. However after 90 secs the form closes by itself but pops up a MessageBox first to let the user know.

Now I'm having a hard time to know why that MessageBox would pop up again every 90 secs after the form is already closed for the first time.

I have a Windows.Forms.Timer for the 90 sec auto close and using Form.Close to close it. I add the forms to a Dictorionary with their ID for some management stuff.

Creating the forms :

MainForm myform = new MainForm();
myform.plate = eventData.iPlate;
myform.tag = eventData.iTag;
formulario.image = eventData.Image;
formulario.PopulateMyFields();
ActivePopUps.Add(eventData.ide, myform);
myform.Show();

Now closing them using the Dictionary

foreach (var popup in ActivePopUps)
{
    if (popup.Key == eventData.some_id)
    {
        try
        {
            popup.Value.Close();
        }
        catch { }
        ActivePopUps.Remove(popup.Key);
    }
}

And the timer created in MainForm

mytimer = new System.Windows.Forms.Timer();
timer_mytimer .Interval = Properties.Settings.Default.ClosingTime; // 90000
mytimer.Tick+=new EventHandler(mytimerEvent);
mytimer.Enabled = true;
mytimer.Start();

And the actual Timer Event

private void mytimerEvent(object sender, EventArgs e)
{
    MessageBox.Show("Hey ! Closing this one");
    this.Close();
}

I believe I could be able to stop the timer before calling .Close() and make it stop but my question is .... isn't Close supposed to do that? Even making a call to .Dispose()? Why does the timer keep working and what else does survive on the background?

1
Hint: if you add timer using form designer you will notice a difference in source code, this line: this.timer1 = new System.Windows.Forms.Timer(this.components);. - Sinatr
this.Close means the form, not the timer. You instantiate the timer from code, so it is an object independent from the form. - Cee McSharpface
Use the mytimer.Enabled = false; to get rid of the timer before you close the form. You can also put it in the Form_Closed event. - Jeroen van Langen
@Sinatr thank you. That was beautiful :) - RRhoads

1 Answers

0
votes

Just to clarify. The correct answer was provided by Sinatr in his comment, so the question is perfectly answered and my code is working fine.

I was missing the following when creating the timer:

this.mytimer = new System.Windows.Forms.Timer(this.components)

By doing this, the timer is linked to the form so that it gets disposed when the Close() is called by the Form.