且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

显示隐藏窗体

更新时间:2023-12-06 09:49:28

当您执行以下操作:

MainMenuForm frmMainMenu = new MainMenuForm();
frmMainMenu.Show();

您正在创建和呈现出的的MainMenuForm的实例。

You are creating and showing a new instance of the MainMenuForm.

为了显示和隐藏你需要保持对它的引用了MainMenuForm的一个实例。即当我做Compact Framework的应用程序,我已经使用Singleton模式,以确保静态类我永远只能有一个表格的一个实例在运行时:

In order to show and hide an instance of the MainMenuForm you'll need to hold a reference to it. I.e. when I do compact framework apps, I have a static classes using the singleton pattern to ensure I only ever have one instance of a form at run time:

public class FormProvider
{
   public static MainMenuForm MainMenu
   {
       get
       {
          if (_mainMenu == null)
          {
            _mainMenu = new MainMenuForm();
          }
          return _mainMenu;
       }
   }
   private static MainMenuForm _mainMenu;
}

现在你可以使用 FormProvider.MainMenu.Show ()来显示窗体和 FormProvider.MainMenu.Hide()来隐藏窗体。

Now you can just use FormProvider.MainMenu.Show() to show the form and FormProvider.MainMenu.Hide() to hide the form.

借助 Singleton模式(感谢的拉撒路中的链接)是管理中的WinForms应用形式,因为这意味着你只有一次创建窗体实例的好方法。第一次的形式是通过其各自的属性来访问,表单被实例化并存储在一个专用变量。

The Singleton Pattern (thanks to Lazarus for the link) is a good way of managing forms in WinForms applications because it means you only create the form instance once. The first time the form is accessed through its respective property, the form is instantiated and stored in a private variable.

例如,你可以使用 FormProvider.MainMenu 第一次,私有变量_mainMenu被实例化。你叫 FormProvider.MainMenu 随后的任何时间,_mainMenu是直接返回远没有被再次实例化。

For example, the first time you use FormProvider.MainMenu, the private variable _mainMenu is instantiated. Any subsequent times you call FormProvider.MainMenu, _mainMenu is returned straight away without being instantiated again.

不过,你不必所有的表单类存储在一个静态实例。你可以只是形式作为公司控制的MainMenu窗体上的一个属性。

However, you don't have to store all your form classes in a static instance. You can just have the form as a property on the form that's controlling the MainMenu.

public partial class YourMainForm : Form
{
   private MainMenuForm _mainMenu = new MainMenuForm();

   protected void ShowForm()
   {
      _mainMenu.Show();
   }

   protected void HideForm()
   {
      _mainMenu.Hide();
   }
}



更新:

刚读 MainMenuForm 是启动窗体。实施类似我上面单身例子类,然后更改您的代码在应用程序的Program.cs文件如下:

Just read that MainMenuForm is your startup form. Implement a class similar to my singleton example above, and then change your code to the following in the Program.cs file of your application:

Application.Run(FormProvider.MainMenu);

您可以再访问 MainMenuForm 从任何地方在通过 FormProvider 类应用程序。

You can then access the MainMenuForm from anywhere in your application through the FormProvider class.