How 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:

Collapse
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:

Collapse
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:

App.MainFormManager.CurrentForm=new Form1();

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值