2013-04-05 94 views
9

我想问一下如何在程序加载时出现加载屏幕(只是图片或其他东西),程序加载完成后会消失。C#WinForm - 加载屏幕

在发烧友版本中,我看到了过程栏(%)的显示。你怎么能这样做,以及你如何计算%显示?

我知道有一个Form_Load()事件,但我没有看到Form_Loaded()事件,或%作为属性/属性的任何地方。

+0

表单载入是什么?你有任何数据库查询操作,cpu密集型操作,你真的需要展示一个“进度条”,或者你只是想要一个启动画面? – 2013-04-05 14:08:50

+0

我想要一个启动画面,但我也想知道进度条。 – CaTx 2013-04-05 19:58:33

回答

26

您只需创建一个表单作为启动画面,然后在主开始显示着陆页并在着陆页加载后关闭此飞溅之前显示它。

using System.Threading; 
using System.Windows.Forms; 

namespace MyTools 
{ 
    public class SplashForm : Form 
    { 
     //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; 
     } 
    } 
} 

和主要程序的功能是这样的:

[STAThread] 
static void Main(string[] args) 
{ 
    SplashForm.ShowSplashScreen(); 
    MainForm mainForm = new MainForm(); //this takes ages 
    SplashForm.CloseForm(); 
    Application.Run(mainForm); 
} 
+0

我可以使用此代码从另一个窗体调用大而慢的窗体吗?像“登录 - >主屏幕”? – 2013-08-07 17:26:18

+0

您的mainScreen是您程序的启动点。所以你需要一个活着的主实例然后你可以。 – JSJ 2013-08-08 10:56:08

+0

谢谢!这是一个很棒的教程! – tkrn 2013-11-18 15:09:08

1

如果你要显示SplashForm不止一次在应用程序中,一定要设置splashForm变量,否则为null你会出错。

static private void CloseFormInternal() 
{ 
    splashForm.Close(); 
    splashForm = null; 
} 
+0

我编辑代码答案。谢谢。 – Pedro77 2017-12-15 01:13:12