Explorerの再起動時にNotifyIconのタスクトレイアイコンを再びセットする。


Description

Explorerのプロセスが何らかの理由で終了し再起動した場合タスクトレイアイコンが消えてしまいます。

NotifyIcon クラスを利用しているときに再びセットする方法を説明します。

How to

Win32の RegisterWindowMessage APIでExplorer.exeが再起動した際に TaskbarCreated メッセージを送ってくるように登録し、ウィンドウプロシージャでそのメッセージをつかむことでExplorer.exeの再起動を知ることが出来ます。

Sample Code

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class
RestoreIconTest : Form
{
	private NotifyIcon _notifyIcon = new NotifyIcon();
	private Int32 _uTaskbarRestartMsg = 0;
	
	public static Int32
	Main(String[] args)
	{
		Application.Run(new RestoreIcon());
		return 0;
	}
	
	public
	RestoreIconTest()
	{
		_notifyIcon.Icon = this.Icon;
		_notifyIcon.Visible = true;
	}
	
	protected override void
	OnClosed(EventArgs e)
	{
		_notifyIcon.Visible = false;
	}
	protected override void
	OnHandleCreated(EventArgs e)
	{
		// タスクトレイのアイコン復活のためのメッセージ登録
		_uTaskbarRestartMsg = RegisterWindowMessage("TaskbarCreated");
		base.OnHandleCreated(e);
	}
	protected override void
	WndProc(ref Message m)
	{
		// タスクトレイのアイコンをセット
		if (m.Msg == _uTaskbarRestartMsg && _uTaskbarRestartMsg != 0)
			_notifyIcon.Visible = true;
		
		base.WndProc(ref m);
	}
	
	[DllImport("user32.Dll", CharSet=CharSet.Auto)]
	private static extern Int32
	RegisterWindowMessage([MarshalAs(UnmanagedType.LPTStr)] String lpString);
}