C# アプリケーションのスタート時にフォームを開かないでシステムトレイに入れる
実装
- Form1にtimerコントロールを貼る。
- timerコントロールのIntervalを20000ミリ秒に設定
- Form1のShowInTaskbarプロパティをFalseに設定
- Program.csを開いて、以下のように変更する。
[STAThread]
static void Main()
{
//ここの2行は変更なし
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//二重起動を防ぐ
//Mutexクラスの作成
//"MyName"の部分を適当な文字列に変える
System.Threading.Mutex mutex =
new System.Threading.Mutex(true, "MyName", out createdNew);
if (createdNew == false)
{
//起動させない
return;
}
using (NotifyIcon icon = new NotifyIcon())
{
icon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);
//フォームのインスタンスを作成する
Form1 form1 = new Form1();
//Form1のNotifyIconメンバーに、このNotifyIconのインスタンスを登録
form1.NotifyIcon = icon;
//システムトレイのアイコンの右クリックメニュー登録
icon.ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("ウィンドウを開く", (s, e) => {form1.ShowForm();}),
new MenuItem("終了", (s, e) => { Application.Exit(); }),
});
icon.Visible = true;
Application.Run();
icon.Visible = false;
}
//ミューテックスを解放する
mutex.ReleaseMutex();
}
Form1の実装
internal NotifyIcon NotifyIcon { get; set; }
private void timer1_Tick(object sender, EventArgs e)
{
//balloonTip表示
NotifyIcon.BalloonTipIcon = ToolTipIcon.Info;
NotifyIcon.BalloonTipTitle = "20秒経ちましたよ!";
NotifyIcon.BalloonTipText = "お知らせの本文ですよ!";
//3秒表示
NotifyIcon.ShowBalloonTip(3000);
}
//アイコン右クリックの「ウィンドウを開く」で呼ばれるメソッド
public void ShowForm()
{
// フォームの表示
this.Visible = true;
if (this.WindowState == FormWindowState.Minimized)
{
// 最小化をやめる
this.WindowState = FormWindowState.Normal;
}
// Notifyアイコン非表示
NotifyIcon.Visible = false;
this.Activate();
}
//フォームのイベント(ボタンクリックなど)で再度システムトレイに格納
private void ShowIconSystemTray()
{
//フォームを非表示に
this.Visible = false;
//最小化
this.WindowState = FormWindowState.Minimized;
//システムトレイのアイコン表示
NotifyIcon.Visible = true;
}