Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

How To Swap Top Level Forms

Rate me:
Please Sign up or sign in to vote.
4.87/5 (21 votes)
25 Jun 2004 89.1K   866   33   17
Use a specialized ApplicationContext to swap top level forms.

The Problem

I recently had a requirement where I needed to change the top level form. The problem is, the ApplicationContext hooks the Form's Close event, so that when you use the Close method to close the current form, the application exits. This is no good!

The Solution

The solution is to implement a specialized ApplicationContext that allows the application to close the current top level form and replace it with a different one. The implementation is quite straight forward:

C#
using System;
using System.Windows.Forms;

namespace ApplicationContextDemo
{
  public class MainFormManager : ApplicationContext
  {
    protected bool exitAppOnClose;

    public Form CurrentForm
    {
      get {return MainForm;}
      set
      {
        if (MainForm != null)
        {
          // close the current form, but don't exit the application
          exitAppOnClose=false;
          MainForm.Close();
          exitAppOnClose=true;
        }
        // switch to the new form
        MainForm=value;
        MainForm.Show();
      }
    }

    public MainFormManager()
    {
      exitAppOnClose=true;
    }

    // when a form is closed, don't exit the application if this is a swap
    protected override void OnMainFormClosed(object sender, EventArgs e)
    {
      if (exitAppOnClose)
      {
        base.OnMainFormClosed(sender, e);
      }
    }
  }
}

In the above code, assigning the CurrentForm property to a Form blocks the OnMainFormClosed method from its usual operation, which is to call ExitThreadCore.

Your main application would look something like this:

C#
using System;
using System.Windows.Forms;

namespace ApplicationContextDemo
{
  public class App
  {
    private static MainFormManager mainFormManager;

    public static MainFormManager MainFormManager
    {
      get {return mainFormManager;}
    }

    public App()
    {
      mainFormManager=new MainFormManager();

      mainFormManager.CurrentForm=new Form1();
      Application.Run(mainFormManager);
    }

    [STAThread]
    static void Main() 
    {
      new App();
    }
  }
}

The above code instantiates the first form, and instead of the typical Application.Run(new Form1) method, the specialized application context is provided.

To swap a form, simply assign a new Form to the CurrentForm property, for example:

C#
App.MainFormManager.CurrentForm=new Form1();

I've provided a demonstration application that illustrates swapping three different top-level forms.

Conclusion

Simple but useful when you need this kind of functionality!

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1308617026-Mar-17 20:24
Member 1308617026-Mar-17 20:24 
QuestionHow do I maintain the size of the form if I previously resized it? Pin
smeng6-Sep-10 0:49
smeng6-Sep-10 0:49 
AnswerRe: How do I maintain the size of the form if I previously resized it? Pin
Marc Clifton6-Sep-10 1:53
mvaMarc Clifton6-Sep-10 1:53 
QuestionMultiple Forms Vs One Form Pin
shubie10-Aug-08 14:19
shubie10-Aug-08 14:19 
Thank you for a great article, it helped me. Can you or anyone please guide of what is the best practice for winform applications development. Should I create a single form and add/remove controls dynamically for the entire application or have multiple forms. If to keep the code more structured I decide to have multiple forms will it be more optimised than having one huge form with all the logic in it?Confused | :confused:
thanks in advance
shubster
AnswerRe: Multiple Forms Vs One Form Pin
Marc Clifton10-Aug-08 14:27
mvaMarc Clifton10-Aug-08 14:27 
GeneralRe: Multiple Forms Vs One Form Pin
shubie10-Aug-08 14:39
shubie10-Aug-08 14:39 
GeneralSystem.ObjectDisposedException: Request for Comment Pin
MillionsterNutzer19-Feb-06 22:18
MillionsterNutzer19-Feb-06 22:18 
GeneralYou save me a lot of time and frustration. Pin
Roger50022-Jan-06 14:09
Roger50022-Jan-06 14:09 
GeneralApplicationContext & SaveFileDialog Pin
gcfischer10-Nov-04 5:09
gcfischer10-Nov-04 5:09 
GeneralRe: ApplicationContext & SaveFileDialog Pin
stimpyjcat22-Nov-05 3:17
stimpyjcat22-Nov-05 3:17 
GeneralRe: ApplicationContext & SaveFileDialog Pin
ADLER112-Oct-08 2:56
ADLER112-Oct-08 2:56 
QuestionHow else to do SDI winform applications? Pin
w_77727-Oct-04 21:27
w_77727-Oct-04 21:27 
AnswerRe: How else to do SDI winform applications? Pin
ADLER112-Oct-08 2:52
ADLER112-Oct-08 2:52 
GeneralApplication.Run() with no Form parameter Pin
Frank Hileman1-Jul-04 7:10
Frank Hileman1-Jul-04 7:10 
GeneralRe: Application.Run() with no Form parameter Pin
belknap4-Mar-10 13:05
belknap4-Mar-10 13:05 
GeneralRe: Application.Run() with no Form parameter Pin
Frank Hileman4-Mar-10 13:27
Frank Hileman4-Mar-10 13:27 
GeneralHandy Pin
Ron Dafoe .26-Jun-04 16:26
Ron Dafoe .26-Jun-04 16:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.