mutexを使ってアプリの二重起動を禁止する方法
Mutexクラスを使う事でアプリの二重起動を禁止することができます。
まずはApp.xamlにStartupとExitのイベントを登録します。
<Application x:Class="Sample.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="Application_Startup" Exit="Application_Exit"> <Application.Resources> </Application.Resources> </Application>
App.xaml.csにStartupとExitのイベントハンドラを追加します。
using System.Threading; // ① private Mutex mutex = new Mutex(false, "ApplicationName"); // ② private void Application_Startup(object sender, StartupEventArgs e) { if (!mutex.WaitOne(0, false)) { MessageBox.Show("アプリケーションは起動済みです。", "アプリの二重起動", MessageBoxButton.OK, MessageBoxImage.Exclamation); mutex.Close(); mutex = null; this.Shutdown(); } // mutexを取得できたら何か処理 } // ③ private void Application_Exit(object sender, ExitEventArgs e) { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); mutex = null; } }
色々端折ってるけど、そこはどうにか脳内補完で。
①でmutexを生成しています。この時にアプリケーション固有の名前(サンプルでは"ApplicationName")を渡します。
②のStartupイベントハンドラ内では、mutexの取得を行い取得できなかった(=二重起動している)場合はメッセージを表示して、アプリを終了するようにしました。
③Exitイベントハンドラ内では、取得したmutexの解放を行います。これを忘れるとmutexを取得したままになって次回起動時に二重起動判定されちゃうので注意!
また、二重起動でShutdown()を読んで終了した時もExitイベントハンドラが呼ばれるので、二重で終了処理を行わないように、nullチェックを入れてます。
ざっくりとこんな感じ。
本当は例外発生したらどうすんだとか、もうちょっと色々考えないといけないんだろうけどね…。