2008-09-09 4 views

Répondre

8

Scott Hanselman answers sur votre question en détails.

4

Voici ce que je suis en train de faire dans le fichier Program.cs de l'application.

// 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, c'est une bonne ressource. J'ai répondu à une question semblable à celle-ci il y a quelque temps. Vous pouvez vérifier mon answer here. Même si c'était pour WPF, vous pouvez utiliser la même logique dans WinForms.

+0

En fait, j'appris ce truc du livre se vend aussi. Mais l'article de Scott est juste parmi mes signets :) – aku

3

Vous pouvez utiliser cette détection et activer votre instance après:

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

Merci, j'aime beaucoup votre solution. – Sharique

Questions connexes