Lets assume I have two forms Form1 and Form2. I need to show Form1 for a while of time (say 5 minutes) and then hide it and show Form2 for another 5 minutes and then hide Form2 and then show Form1 and so on …
How can I do that in C++/CLI or C#?
Off the top of my head, I’d probably do something like this (C# example provided)
In usage, when you create Form1 and Form2, you can hold a reference to this in one of the fields of Form1/Form2 and when you close Form1/Form2, just dispose it.
e.g. something like:
There are a couple of things to note:
Use of Form.Invoke
As the timer is essentially running in a separate thread, it’s important to use the Invoke methods of the forms or you’ll get a cross thread exception.
Potential Race Condition
If the time interval is really small, the elapsed event can fire multiple times. Although this would be a silly thing to do from a user experience point of view, the critical issue is if the Timer_Elapsed event is called quickly in succession after Form2 has been closed – it’s possible to get a null reference exception. The same could potentially happen if the app is shutting down while the Timer_Elapsed event is called – the best thing to do here is to Dispose the SwitchForms class (or add a Stop method) so you can get rid of the timer before the app closes.
I could then also put SwitchForms in my startup class for example, although I’d have to be extra careful to then check that Form1 and Form2 haven’t already been disposed and so on.
You could also embed the code of SwitchForms into either Form1 or Form2 for simplicity. You’ll also need to think about what happens if either Form1 or Form2 are closed independently as otherwise the timed event will throw an exception.
In my example, I simply reshow Form1 if Form2 is closed, and if Form1 is closed, the app exits.