アプリの多重起動を防止する
アプリの多重起動防止をしてみました。
↓のサイトを参考にしてます。
http://nine-works.blog.ocn.ne.jp/blog/2011/01/wpf_06c9.html
開始時にMutexを使って多重起動のチェックをして、アプリ終了時にMutexの解放をすればよいらしい。
XAMLにイベントハンドラの設定を書くのが面倒なので、StartupとExitのイベントハンドラではなく、AppクラスのOnStartupとOnExitをオーバーライドして、Mutexの作成と解放をしました。
App.xaml.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace SingleInstanceApp { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { private Mutex mutex = new Mutex(false, "SingleInstanceApp"); protected override void OnStartup(StartupEventArgs e) { if (mutex.WaitOne(0, false) == false) { // すでに起動しているので終了する MessageBox.Show("多重起動はできません。"); mutex.Close(); mutex = null; this.Shutdown(); } base.OnStartup(e); } protected override void OnExit(ExitEventArgs e) { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } base.OnExit(e); } } }