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

C# 激活单实例应用程序的主窗体,c#,.net,winforms,C#,.net,Winforms,在C#Windows窗体应用程序中,我想检测该应用程序的另一个实例是否已经在运行。 如果是,请激活正在运行的实例的主窗体并退出此实例 实现这一点的最佳方法是什么?以下是我目前在应用程序的Program.cs文件中所做的工作 // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or mini

在C#Windows窗体应用程序中,我想检测该应用程序的另一个实例是否已经在运行。 如果是,请激活正在运行的实例的主窗体并退出此实例


实现这一点的最佳方法是什么?

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

斯科特·汉斯曼详细回答了你的问题。

阿库,这是一个很好的资源。不久前我回答了一个类似的问题。你可以查我的电话号码。即使这是针对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

其实我也是从书中学到这个技巧的。但是Scott的文章就在我的书签中:)谢谢,我真的很喜欢你的解决方案。