C# でアプリケーションの多重起動を禁止するコードを紹介します。
環境
WPF App .NET Core 3.1

使い方
App.xaml.cs の OnStartup関数をオーバーライドして、下記のコードの様に修正します。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| using System.Reflection; using System.Threading; using System.Windows;
namespace WpfApp1 { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { // ミューテックス作成 var mutex = new Mutex(false, Assembly.GetExecutingAssembly().GetName().Name);
// ミューテックスの所有権を要求 if (!mutex.WaitOne(0, false)) { MessageBox.Show("このアプリケーションは多重起動出来ません。"); Shutdown(); } } } }
|
実行
多重起動のテストをするため、デバッグではなく実行ファイルを直接起動します。ビルド結果が保存されているディレクトリを開き、プログラムを起動します。

1つ目のプログラムを起動している状態で、2つ目のプログラムを起動させると、メッセージボックスが表示されて、多重起動が出来ない様になっています。

参考
https://www.ipentec.com/document/csharp-singleexec