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

Dea*_*ill 7 .net c# winforms

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

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

aku*_*aku 8

Scott Hanselman详细回答了你的问题.


Dea*_*ill 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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)