激活单实例应用程序的主窗体

9
在一个C# Windows Forms应用程序中,我想检测另一个实例是否已经在运行。 如果是,激活正在运行的实例的主窗体并退出此实例。 实现这个功能的最佳方法是什么?
4个回答

8

Scott Hanselman在答案中详细回答了你的问题。


5

以下是我目前在应用程序的 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)
    {
    }
}

3
您可以使用此检测并在之后激活您的实例:
        // 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

-1

Aku,这是一个很好的资源。我以前回答过类似的问题。你可以在这里查看我的答案。虽然这是针对 WPF 的,但你可以在 WinForms 中使用相同的逻辑。


其实我也是从Sells的书中学到了这个技巧。但Scott的文章只是我的书签之一 :) - aku

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接