次のコードは、アプリケーション(以下の例ではMainForm()と呼ばれます)がロードまたは初期化されている間に、別のスレッドで「スプラッシュ画面」を起動します。まず、「main()」メソッド(名前を変更していない限り、program.csファイル)でスプラッシュ画面を表示する必要があります。これは、起動時にユーザーに表示するWinFormまたはWPFフォームになります。これは、次のようにmain()から起動します。
[STAThread]
static void Main()
{
// Splash screen, which is terminated in MainForm.
SplashForm.ShowSplash();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Run UserCost.
Application.Run(new MainForm());
}
SplashScreenコードには、次のようなものが必要です。
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スレッドから情報を取得するか、純粋に美的な性質で作業する必要があります。アプリケーションが初期化されたときにスプラッシュ画面を終了して閉じるには、デフォルトのコンストラクター内に以下を配置します(必要に応じてコンストラクターをオーバーロードできます)。
public MainForm()
{
// ready to go, now initialise main and close the splashForm.
InitializeComponent();
SplashForm.CloseSplash();
}
上記のコードは、比較的簡単に理解できるはずです。
これがお役に立てば幸いです。