自分用メモ
WindowsForms アプリで実装していた、ミューテックスによる多重起動防止のコードを WPF に書き換えてみた
WindowsForms ではこんな感じで記述していたものを、
[Guid( "04669F2E-5017-4723-B3A1-DFF6200D8DA4" )]
static class Program
{
private static Mutex m_SingleLock = null;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
// 多重起動の防止
Attribute attribute = Attribute.GetCustomAttribute( typeof( Program ), typeof( GuidAttribute ) );
if( (m_SingleLock =
SingleInstanceLock( (new Guid( ((GuidAttribute)attribute).Value )).ToString() )) == null ) {
MessageBox.Show( "アプリケーションは既に実行中です。", "起動エラー",
MessageBoxButtons.OK, MessageBoxIcon.Information );
return;
}
// フォームの作成
Application.Run( new FormMain() );
}
private static Mutex SingleInstanceLock( string LockName )
{
bool CreatedNew;
try {
// ミューテックスの作成
Mutex SingleLock = new Mutex( true, LockName, out CreatedNew );
if( !CreatedNew )
return null;
return SingleLock;
}
catch {
return null;
}
}
}
WPF ではこんな感じに書き換えます
[Guid( "04669F2E-5017-4723-B3A1-DFF6200D8DA4" )]
public partial class App : Application
{
private readonly Mutex m_SingleLock = null;
public App()
{
// 多重起動の防止
Attribute attribute = Attribute.GetCustomAttribute( typeof( App ), typeof( GuidAttribute ) );
if( (m_SingleLock = SingleInstanceLock( (new Guid( ((GuidAttribute)attribute).Value )).ToString() )) == null ) {
MessageBox.Show( "アプリケーションは既に実行中です。", "起動エラー",
MessageBoxButton.OK, MessageBoxImage.Information );
this.Shutdown();
}
}
private Mutex SingleInstanceLock( string LockName )
{
bool CreatedNew;
try {
// ミューテックスの作成
Mutex SingleLock = new Mutex( true, LockName, out CreatedNew );
if( !CreatedNew )
return null;
return SingleLock;
}
catch {
return null;
}
}
}
VisualStudio で WPF アプリケーションを作成した際に作成される、App.xaml.cs を開き、App クラスにコンストラクタを追加しています
あとは WindowsForms アプリと同じく App クラス内に、多重起動防止用のミューテックスが既に使用されているかを判定するための関数を追加するだけで、ほぼ WindowsForms アプリと同じです
ミューテックスに関連付けている文字列については、上記の例ではクラスに Guid を関連付けてそれを設定していますが、一般的には他のアプリケーションと衝突しないようなユニークな名称を直接 LockName に指定します
わたしはアプリケーションごとに毎回名称を考えて付けるのが面倒なので、Guid を設定する方法をとるのが好みです
ただし、WPF では Guid 属性を記述してもインテリセンスが働かないようなので、「using System.Runtime.InteropServices;」を記述してあげる必要があるようです
※WPF 版の多重起動防止のコードは、きちんと検証していませんので利用される場合は独自に検証してください
コメントを残す
コメントを投稿するにはログインしてください。