C#Windowsフォームアプリケーションで、アプリケーションの別のインスタンスが既に実行されているかどうかを検出したいと考えています。 その場合は、実行中のインスタンスのメインフォームをアクティブにして、このインスタンスを終了します。単一インスタンスアプリケーションのメインフォームの有効化
これを達成する最も良い方法は何ですか?
C#Windowsフォームアプリケーションで、アプリケーションの別のインスタンスが既に実行されているかどうかを検出したいと考えています。 その場合は、実行中のインスタンスのメインフォームをアクティブにして、このインスタンスを終了します。単一インスタンスアプリケーションのメインフォームの有効化
これを達成する最も良い方法は何ですか?
Scott Hanselman answers詳細については、ご質問ください。
ここでは、私が現在アプリケーションのProgram.csファイルで行っていることを示します。
// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
static void Main()
{
try
{
// If another instance is already running, activate it and exit
Process currentProc = Process.GetCurrentProcess();
foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))
{
if (proc.Id != currentProc.Id)
{
ShowWindow(proc.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(proc.MainWindowHandle);
return; // Exit application
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
catch (Exception ex)
{
}
}
Aku、それは良いリソースです。私はこれに似た質問にしばらく前に答えました。私のanswer hereをチェックすることができます。これはWPF用ですが、WinFormsでも同じロジックを使用できます。
あなたは、このような検出を使用して、それの後にあなたのインスタンスを起動することができます。
// Detect existing instances
string processName = Process.GetCurrentProcess().ProcessName;
Process[] instances = Process.GetProcessesByName(processName);
if (instances.Length > 1)
{
MessageBox.Show("Only one running instance of application is allowed");
Process.GetCurrentProcess().Kill();
return;
}
// End of detection
ありがとう、私はあなたのソリューションが本当に好きです。 – Sharique
実は私もセルズ帳からこのトリックを学びました。しかしスコットの記事は私のブックマークの中に座っているだけです:) – aku