65.9K
CodeProject 正在变化。 阅读更多。
Home

如何交换顶层窗体

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.87/5 (19投票s)

2004年6月26日

viewsIcon

92264

downloadIcon

868

使用专门的 ApplicationContext 来交换顶级窗体。

问题

我最近有一个需求,需要更改顶级窗体。问题是,ApplicationContext 会挂钩 FormClose 事件,所以当你使用 Close 方法关闭当前窗体时,应用程序会退出。这不行!

解决方案

解决方案是实现一个专门的 ApplicationContext,它允许应用程序关闭当前的顶级窗体并将其替换为另一个窗体。实现起来非常简单。

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);
      }
    }
  }
}

在上面的代码中,将 CurrentForm 属性赋值给一个 Form 会阻止 OnMainFormClosed 方法执行其通常的操作,即调用 ExitThreadCore

你的主应用程序看起来像这样

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();
    }
  }
}

上面的代码实例化了第一个窗体,并且没有使用典型的 Application.Run(new Form1) 方法,而是提供了专门的应用程序上下文。

要交换窗体,只需将一个新的 Form 赋值给 CurrentForm 属性即可,例如

App.MainFormManager.CurrentForm=new Form1();

我提供了一个演示应用程序,它演示了交换三个不同的顶级窗体。

结论

简单但有用,当你需要这种功能时!

参考文献

© . All rights reserved.