Close form from another topic

I have a manager class that runs a form using the ShowDialog function. Now I am triggering an event (for example, a timer) and would like the manager to close the form when the timer expires.

I used 2 classes:

namespace ConsoleApplication3 { class Manager { Timer UpdTimer = null; readonly int REFRESH_STATUS_TIME_INTERVAL = 5000; Form1 form1; public Manager() { } public void ManageTheForms() { UpdTimer = new Timer(REFRESH_STATUS_TIME_INTERVAL); // start updating timer //UpdTimer.Interval = REFRESH_STATUS_TIME_INTERVAL; UpdTimer.Elapsed += new ElapsedEventHandler(PriorityUpdTimer_Elapsed); UpdTimer.Start(); form1 = new Form1(); form1.ShowDialog(); } public void PriorityUpdTimer_Elapsed(object source, ElapsedEventArgs e) { UpdTimer = null; form1.closeFormFromAnotherThread(); } } } 

Form1 Class:

 namespace ConsoleApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { } delegate void CloseFormFromAnotherThread(); public void closeFormFromAnotherThread() { if (this.InvokeRequired) { CloseFormFromAnotherThread del = new CloseFormFromAnotherThread(closeFormFromAnotherThread); this.Invoke(del, new object[] { }); } else { this.Close(); } } } 

}

+4
source share
1 answer

If I'm right, you want to close the form when the timer stops.

So I do it:

 System.Threading.Timer formTimer; 

I use a boolean to see if the timer is on

 public Boolean active { get; set; } 

Create this function:

 public void timerControl() { if (!active) formTimer = new System.Threading.Timer(new TimerCallback(TimerProc)); try { formTimer.Change(REFRESH_STATUS_TIME_INTERVAL, 0); } catch {} active = true; } 

To end the timer, you need the TimerProc function, which is called when creating a new timer:

 private void TimerProc(object state) { System.Threading.Timer t = (System.Threading.Timer)state; t.Dispose(); try { CloseScreen(); } catch{} } 

To make programming easier for me, I made the CloseScreen () function:

 public void CloseScreen() { if (InvokeRequired) { this.Invoke(new Action(CloseScreen), new object[] { }); return; } active = false; Close(); } 

Put all these functions in your form class and just use timerControl to activate the timer. You can access it from your Manager class: Form1.TimerControl(); Or put it in an event handler, successfully!

+1
source

All Articles