How to Dispose a Form in C# without closing the Application

As a good programmer you should be thinking about the resources your software uses and be as gentle as possible on the Computer’s memory.

With C# you would be probably clearing the objects you no longer need from the memory using the Dispose method.

But if you dispose a Windows Form in C#, the whole application will quit! WHY?

That’s because by default C# select a start up form defined in the Program.cs file like this:

Application.Run(new Form1());

So to fix this just delete the “new Form1()” , and load up an instance of the form you want from Main() in the Program.cs so the whole thing will look like:

Form1 frm1 = new Form1();
frm1.Show();
Application.Run();

Now you can load and dispose forms all you want without the application quiting on you:)

Share
  • maysam

    Salam

    I’m from Iran looking for a friend in syria
    If you reside in syria now, please accept my invitation and send me an email

    Maysam

  • Jonathan

    Hi there, i try to use your methods to startup the form but the application.run keep saying it do not have a overload method.

    Please help.

    Form1 Page1 = new Form1();
    Page1.Show();
    Application.Run();<–Error

  • Hey Jonathan,

    I’ve just tried it again, it is working normally as I said. I’m using .Net 2 with Visual Studio 2008. What about you ?

  • GC

    Hi Hasan,

    Ive notice a problem with your solution. The coding works yes, but when all the forms close, what happens to the actual application?

    That is where the problem is. The program.exe is still using memory even though no forms are open.

  • Hello GC,

    Thanks for your comment 🙂

    This problem is happening to you because you are not handling opening and closing form properly.

    For example, if you have Form1 and Form2 and you want to hide Form1 and show Form2; what you should do is create a new instance of the Form2 show it AND you have to dispose the Form1 … like:

    Form2 frm2 = new Form2;

    frm2.Show;

    this.Dispose();

    In addition to that, add the following code to the “FormClosing” event to all of the forms so the application exits and clears itself from the memory when the user hit the close button (Ctrl + F4 or the X button on the top of the window):

    Application.Exit();

    Hope that helps 😉

    And let me know if you need something else.

  • Manu

    Thanks for your tip!!!

    It worked gr8!!

  • You are most welcome Manu, I’m glad it worked for you. Thanks for your comment 🙂

  • Eric

    What framework is this valid for? I am utilizing the .NET Framework v1.1 for some legacy Windows Mobile development and I receive a compiler error saying that no overload of Application.Run receives 0 arguments.

  • Anonymous

    Hello Eric. This was long time ago, but as I recall it was .NET framework 2.