C#winforms启动(Splash)表单没有隐藏
我有一个winforms应用程序,我在其中使用2个表单来显示所有必要的控件。 第一个表单是一个启动画面,它告诉用户它正在加载等等。所以我使用以下代码:
Application.Run( new SplashForm() );
一旦应用程序完成加载,我希望SplashForm隐藏或我发送到后面和主要显示。 我目前正在使用以下内容:
private void showMainForm() { this.Hide(); this.SendToBack(); // Show the GUI mainForm.Show(); mainForm.BringToFront(); }
我所看到的是显示了MainForm,但SplashForm仍然可以在“顶部”显示。 我目前正在做的是点击MainForm手动将它带到前面。 有关为何发生这种情况的任何想法?
可能你只想关闭飞溅forms,而不是发送回来。
我在一个单独的线程上运行splash表单(这是SplashForm类):
class SplashForm { //Delegate for cross thread call to close private delegate void CloseDelegate(); //The type of form to be displayed as the splash screen. private static SplashForm splashForm; static public void ShowSplashScreen() { // Make sure it is only launched once. if (splashForm != null) return; Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm)); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Start(); } static private void ShowForm() { splashForm = new SplashForm(); Application.Run(splashForm); } static public void CloseForm() { splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal)); } static private void CloseFormInternal() { splashForm.Close(); splashForm = null; } ... }
并且主程序function如下所示:
[STAThread] static void Main(string[] args) { SplashForm.ShowSplashScreen(); MainForm mainForm = new MainForm(); //this takes ages SplashForm.CloseForm(); Application.Run(mainForm); }
这对于防止您的闪屏在关闭后阻止您的焦点并将主表单推送到后台至关重要:
protected override bool ShowWithoutActivation { get { return true; } }
将此添加到您的splash表单类。
如果我理解正确,您应该只在主表单上使用Application.Run。 因此,要么首先使用以下内容显示您的启动:
using(MySplash form = new MySplash()) form.ShowDialog();
然后随时在MySplash中手动关闭它。
或者在主窗体中显示它加载事件处理程序,然后等待它关闭或其他任何东西,直到你让Load方法完成。 (可能在显示之前将Visible设置为false,然后再返回true。
我相信这可能是我目前设计中的一个设计缺陷!
我认为实现我需要的最好方法是让所有东西都能从MainForm中控制出来。 所以我可以用:
Application.Run(new MainForm());
然后,这将负责显示/更新/隐藏SplashScreen。 通过这种方式,我可以与MainForm管理的系统的其余部分进行必要的复杂操作。