更新时间:2023-12-06 16:19:10
有有多种创建启动屏幕的方法:
There are different ways of creating splash screens:
您可以通过在其他UI线程上显示表单并隐藏来自己显示实现功能
You can show implement the feature yourself by showing a form on a different UI thread and hiding it after the main from loaded successfully.
在这篇文章中,我将展示这两种解决方案的示例。
In this post I'll show an example of both solutions.
注意:那些在数据加载过程中显示加载窗口或加载
gif动画的人可以看看这篇文章:显示在其他线程中加载数据期间的加载动画
选项1-使用WindowsFormsApplicationBase闪屏功能
Microsoft.VisualBasic.dll
对项目的引用。 MyApplication
通过从 WindowsFormsApplicationBase
OnCreateMainForm
并分配所需的成为 MainForm
属性的启动表单。覆盖 OnCreateSplashScreen
并将要显示为初始屏幕的表单分配给 SplashScreen
属性。
Microsoft.VisualBasic.dll
to your project.MyApplication
class by deriving from WindowsFormsApplicationBase
OnCreateMainForm
and assign the from that you want to be the startup form to MainForm
property.Override OnCreateSplashScreen
and assign the form that you want to show as splash screen to SplashScreen
property.
在您的 Main
方法中,创建 MyApplication
的实例并调用其运行
方法。
In your Main
method, create an instance of MyApplication
and call its Run
method.
示例
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(true);
var app = new MyApplication();
app.Run(Environment.GetCommandLineArgs());
}
}
public class MyApplication : WindowsFormsApplicationBase
{
protected override void OnCreateMainForm()
{
MainForm = new YourMainForm();
}
protected override void OnCreateSplashScreen()
{
SplashScreen = new YourSplashForm();
}
}
选项2-使用不同的UI线程
您可以通过在其他UI线程中显示初始屏幕来自己实现此功能。为此,您可以预订 Program
类中主窗体的 Load
事件,并显示并关闭启动画面
You can implement the feature yourself by showing the splash screen in a different UI thread. To do so, you can subscribe to Load
event of the main form in Program
class, and show and close your splash screen there.
示例
using System;
using System.Threading;
using System.Windows.Forms;
static class Program
{
static Form SplashScreen;
static Form MainForm;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Show Splash Form
SplashScreen = new Form();
var splashThread = new Thread(new ThreadStart(
() => Application.Run(SplashScreen)));
splashThread.SetApartmentState(ApartmentState.STA);
splashThread.Start();
//Create and Show Main Form
MainForm = new Form8();
MainForm.Load += MainForm_LoadCompleted;
Application.Run(MainForm);
}
private static void MainForm_LoadCompleted(object sender, EventArgs e)
{
if (SplashScreen != null && !SplashScreen.Disposing && !SplashScreen.IsDisposed)
SplashScreen.Invoke(new Action(() => SplashScreen.Close()));
MainForm.TopMost = true;
MainForm.Activate();
MainForm.TopMost = false;
}
}
注意:显示光滑的边缘自定义形状的初始屏幕,请看
这篇文章: Windows窗体透明背景
图像。