下面的代码在单独的线程上启动一个“启动画面”,而您的应用程序(在我的示例中,它被称为MainForm())加载或初始化。首先在你的“main()”方法中(在你的program.cs文件中,除非你重命名了它),你应该显示你的启动画面。这将是一个WinForm或WPF表单,您希望在启动时向用户显示。这是主要推出()如下:
[STAThread]
static void Main()
{
// Splash screen, which is terminated in MainForm.
SplashForm.ShowSplash();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Run UserCost.
Application.Run(new MainForm());
}
在你的闪屏的代码,你需要像下面这样:
public partial class SplashForm : Form
{
// Thredding.
private static Thread _splashThread;
private static SplashForm _splashForm;
public SplashForm()
{
InitializeComponent();
}
// Show the Splash Screen (Loading...)
public static void ShowSplash()
{
if (_splashThread == null)
{
// show the form in a new thread
_splashThread = new Thread(new ThreadStart(DoShowSplash));
_splashThread.IsBackground = true;
_splashThread.Start();
}
}
// Called by the thread
private static void DoShowSplash()
{
if (_splashForm == null)
_splashForm = new SplashForm();
// create a new message pump on this thread (started from ShowSplash)
Application.Run(_splashForm);
}
// Close the splash (Loading...) screen
public static void CloseSplash()
{
// Need to call on the thread that launched this splash
if (_splashForm.InvokeRequired)
_splashForm.Invoke(new MethodInvoker(CloseSplash));
else
Application.ExitThread();
}
}
这将启动飞溅的形式在一个单独的后台线程允许你继续同时呈现您的主应用程序。要显示关于加载的消息,您必须从主UI线程获取信息,或者以纯粹的审美性质工作。为了完成并关闭闪屏下来的时候你的应用程序已被初始化你把默认的构造函数中以下(你可以重载的构造函数,如果你想):
上面的代码应该是比较容易跟随。
我希望这会有所帮助。
你为什么不只是删除的睡眠?这是什么阻止用户界面。 – usr 2012-08-04 10:32:38
我已经尝试通过删除睡眠,循环然后阻止用户界面 – greatmajestics 2012-08-04 10:37:32
好吧,当然也删除循环;-)解除屏蔽UI线程需要从您的事件处理程序返回。 – usr 2012-08-04 10:38:44