Search code examples
c#formstimertimed-events

Close form in a timed event


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

Solution

  • 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();
    }