Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set Application Shutdown Mode in a C# Windows Forms Project?

I have just switched from VB.Net to C# and am writing a windows application. In VB.net you could easily change the Shutdown Mode by selecting the properties of the project and moving to a dropdown where you could choose between "When startup form closes" and "When last form closes". Please help me to find the equivalent in C#.

By the way, I'm using VS 2010.

like image 630
marai Avatar asked Nov 04 '11 01:11

marai


2 Answers

In c# the easiest trick to achieve this is to change the entry point of the application in the "program.cs" file. This entry form should be hidden on startup,but will call the main form. Then call the Application.Exit(); function in the close procedure in any other form/class.

Sample pseudo code below

program.cs

//edit this line
Applcation.Run(startupForm);

StratupForm.cs

//startup method
StartupForm_load (object e)
{
this.Hide();
MainForm mainForm = new MainForm();
mainForm.show();
}

MainForm.cs

 //application exit method
    MainFormExit_close (object e)
    {
     Application.Exit();
    }

You should probably implement a neater way to manage and keep track of open forms later in your program

like image 122
Ifewalter Avatar answered Nov 14 '22 23:11

Ifewalter


It's not the first thing you might look for, but if you look at the docs for Application.Run(ApplicationContext), you'll find sample code to do exactly what you're asking for: exit the application when the last form is closed.

like image 41
Joe White Avatar answered Nov 15 '22 00:11

Joe White