2008-09-09 10 views

Respuesta

8

Scott Hanselman answers pregunta sobre usted.

4

Esto es lo que estoy haciendo actualmente en el archivo Program.cs de la aplicación.

// 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

Aku, ese es un buen recurso. Respondí una pregunta similar a ésta hace un tiempo. Puedes consultar mi answer here. Aunque esto fue para WPF, puede usar la misma lógica en WinForms.

+0

En realidad he aprendido este truco del libro se vende también. Pero el artículo de Scott solo se encuentra entre mis marcadores :) – aku

3

Puede utilizar dicha detección y activar la instancia después de que:

 // 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

Gracias, realmente me gusta su solución. – Sharique

Cuestiones relacionadas