2008-09-09 26 views
7

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

达到此目的的最佳方法是什么?

回答

8

Scott Hanselman answers在您的问题的细节。

4

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

阿库,这是一个很好的资源。我回答了一个类似于这个问题的问题。你可以检查我的answer here。尽管这是用于WPF的,但您可以在WinForms中使用相同的逻辑。

+0

其实我学到卖出书这一招了。但斯科特的文章只是我的书签中的座位:) – aku 2008-09-09 13:50:06

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 
+0

谢谢,我真的很喜欢你的解决方案。 – Sharique 2010-10-27 07:07:55

相关问题