激活单实例应用程序的主要形式

时间:2020-03-05 18:50:03  来源:igfitidea点击:

在CWindows Forms应用程序中,我想检测该应用程序的另一个实例是否已经在运行。
如果是这样,请激活正在运行的实例的主要形式并退出该实例。

实现此目标的最佳方法是什么?

解决方案

回答

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

回答

Scott Hanselman会详细回答问题。

回答

Aku,那是很好的资源。不久前,我回答了一个与此类似的问题。我们可以在这里查看我的答案。即使这是用于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