【发布时间】:2008-09-09 13:35:10
【问题描述】:
在 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)
{
}
}
【讨论】:
您可以使用此类检测并在此之后激活您的实例:
// 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
【讨论】:
Aku,这是一个很好的资源。不久前我回答了一个与此类似的问题。你可以查看我的answer here。即使这是针对 WPF 的,您也可以在 WinForms 中使用相同的逻辑。
【讨论】: