Close form in a timed event

3.8k views Asked by At

I can't make the form "frmDOOR" close in 'OnTimeEvent'.

frmDOOR close = new frmDOOR
close.close();

It's not working. It even makes the timedevent repeat itself even though I have autoreset set to false. I hope you can find out what I'm doing wrong, it's driving me crazy!

public partial class frmDOOR : BASEFORM
{
    public frmDOOR()
    {
        InitializeComponent();
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 1000;
        aTimer.AutoReset = false;
        aTimer.Enabled = true;           
    }

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {                
        frmUser regform = new frmUser();
        regform.StartPosition = FormStartPosition.CenterParent;            
        regform.ShowDialog();
    }        
}
2

There are 2 answers

0
rene On BEST ANSWER

If you want to close the current instance of your form you simply refer to it with this (that isn't even needed as you're calling its own methods).

Use the System.Windows.Forms.Timer to overcome cross-thread issues.

System.Windows.Forms.Timer aTimer = new System.Windows.Forms.Timer();

public frmDOOR()
{
    InitializeComponent();
    aTimer.Tick += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 1000;
    aTimer.Enabled = true;           
}



private static void OnTimedEvent(object source, EventArgs e)
{                
    this.Close();
    // or even shorter just Close();
    // let's stop the timer as well
    aTimer.Stop();

    frmUser regform = new frmUser();
    regform.StartPosition = FormStartPosition.CenterParent;            
    regform.ShowDialog();
}
1
joe On

Don't use a System.Timers.Timer, it calls its event on a different thread.
Simply use a Windows.Forms.Timer. You can create it within the form desinger and also its Tick event. The timer isnt' very precise, but good enough for most cases.