スプラッシュウィンドウを表示する - C#

アプリケーション起動時に時間がかかる場合、アプリケーションタイトルやロゴなどが入ったウィンドウ(スプラッシュウィンドウ)を表示することがあります。この記事では、C#でスプラッシュウィンドウを表示するコードを紹介します。

概要

スプラッシュウィンドウを表示するには、スプラッシュウィンドウ用のフォームを作成し、アプリケーション起動時にフォームを表示することで実現できます。

プログラム例

UI

以下のUIを準備します。

メインフォーム


スプラッシュウィンドウ

  • StartPositionプロパティを CenterScreen
  • FormBorderStyleを None に設定します。

コード

Progarm.csにコードを記述します。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace SplashWindow
{
  static class Program
  {
    /// <summary>
    /// アプリケーションのメイン エントリ ポイントです。
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      FormSplash fs = new FormSplash();
      fs.Show();
      fs.Refresh();
      Thread.Sleep(3000);//時間のかかる処理
      fs.Close();

      Application.Run(new FormMain());
    }
  }
}
FormMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SplashWindow
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void FormMain_Load(object sender, EventArgs e)
    {

    }
  }
}
FormSplash.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SplashWindow
{
  public partial class FormSplash : Form
  {
    public FormSplash()
    {
      InitializeComponent();
    }

    private void FormSplash_Paint(object sender, PaintEventArgs e)
    {
      Rectangle rect = new Rectangle(0,0, this.Width, this.Height);
      ControlPaint.DrawBorder3D(e.Graphics, rect, Border3DStyle.Raised);
    }
  }
}

解説

Program.cs

下記コードにて、スプラッシュフォームを表示します。
FormSplash fs = new FormSplash();
fs.Show();
fs.Refresh();

Main関数内に時間のかかる処理を記述します。今回はSleepメソッドで代用しました。
Thread.Sleep(3000);//時間のかかる処理

処理終了後、スプラッシュウィンドウを閉じメインフォームを表示します。
fs.Close();
Application.Run(new FormMain());

FormMain.cs

このファイルにはコードを追加しません。

FormSplash.cs

フォームのPaintイベントに画面描画のコードを追加します。今回はDrawBorder3D()メソッドを呼び出し立体的な枠を描画しています。

実行結果

アプリケーションを起動すると下図のスプラッシュウィンドウが表示されます。


3秒ほどするとスプラッシュウィンドウが消え、メインウィンドウが表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2011-11-25
iPentec all rights reserverd.