Typically, the right way to get your application to do something different from the standard (open a form, wait for it to close, and then exit) is to make a class that inherits from ApplicationContext . Then you pass an instance of your class to the Application.Run method. When the application should close, call ExitThread() from your class.
In this case, you can instantiate the three forms when the application loads and register a handler for your Closed events. When each form is closed, the handler checks for any other forms and, if it does not close the application.
The example in MSDN does two things:
- opening several forms and exiting the application when they are all closed.
- saving the last size and position of the form when closing each form.
The simplest example that closes the application only after closing all forms:
class MyApplicationContext : ApplicationContext { private void onFormClosed(object sender, EventArgs e) { if (Application.OpenForms.Count == 0) { ExitThread(); } } public MyApplicationContext() {
Then your Program class looks like this:
static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyApplicationContext()); } }
Obviously, the logic for closing the application can be customized - any forms are still open or only one of these three types or only the first three instances (which requires a link to the first three instances, possibly in a List<Form> ).
Re: global event to create each form - this looks promising.
A similar example is here .
source share