How to show a welcome screen before the main screen of a winforms application is shown?

时光毁灭记忆、已成空白 提交于 2020-07-10 03:12:26

问题


I want to load a welcome screen on the startup of the application then the user clicks a button on the welcome screen and then closes the welcome screen. Finally then shows the main screen.

static void Main() //startup method being called
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  Application.Run(new ACM812_DB()); // welcome screen
}

When a button is clicked on the welcome screen it then hides the welcome window and then brings up the main window. As shown below.

private void button1_Click(object sender, EventArgs e)
{
   Form1 form1 = new Form1();
   form1.Show(); // main window
   this.Hide();
}

It does work successfully but is it the correct way to implement this?

Updated code:

Main form startup (MainForm.cs)

namespace System
{
  public partial class MainForm : Form
  {
     private void MainForm_Load(object sender, EventArgs e)
     {
        WelcomeForm.Run(this);
     }

     public MainForm()
     {
        InitializeComponent();
     }

   }
 }

Welcome screen then called

public partial class WelcomeForm : Form
{
    static private Form Sender;

    static public void Run(Form sender)
    {
      if (sender == null) 
      throw new ArgumentNullException();
      Sender = sender;
      new WelcomeForm().ShowDialog();
    }

    private void ButtonClose_Click(object sender, EventArgs e)
    {
      Close();
    }
}

回答1:


Not really a good pattern.

Because the Application instance is made to manage the main form that is made to be "alive" until the application exit.

You can show the welcome screen in the main form load as a dialog:

MainForm.cs

private void MainForm_Load(object sender, EventArgs e)
{
  WelcomeForm.Run(this);
}

WelcomeForm.cs

public partial class WelcomeForm : Form
{
  static private Form Sender;
  static public void Run(Form sender)
  {
    if (sender == null) 
      throw new ArgumentNullException();
    Sender = sender;
    new WelcomeForm().ShowDialog();
  }
  private void ButtonClose_Click(object sender, EventArgs e)
  {
    Close();
  }
}

Hence the welcome screen can control the main form and set any public data needed.

The MainForm is created in the Main method and the Application instance take control. So the load event of MainForm is called and this last calls the Run static method of the WelcomeForm that creates an instance and shows it as a dialog. This stop the MainForm, not shown yet, until the welcome screen is closed. Then the MainForm can be shown.

It is one way among others, but it is simple, if it matches your goal.



来源:https://stackoverflow.com/questions/62740385/how-to-show-a-welcome-screen-before-the-main-screen-of-a-winforms-application-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!