2008-09-09 15 views

Trả lời

8

Scott Hanselman answers về bạn câu hỏi chi tiết.

4

Đây là những gì tôi hiện đang làm trong tệp Program.cs của ứng dụng.

// 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, đó là một tài nguyên tốt. Tôi trả lời một câu hỏi tương tự câu hỏi này trong khi quay lại. Bạn có thể kiểm tra số answer here của tôi. Mặc dù điều này là dành cho WPF, bạn có thể sử dụng cùng một logic trong WinForms.

+0

Thật sự tôi học được thủ thuật này từ Sells cuốn sách quá. Nhưng bài viết của Scott chỉ nằm trong số các dấu trang của tôi :) – aku

3

Bạn có thể sử dụng phát hiện như vậy và kích hoạt ví dụ của bạn sau khi nó:

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

Cảm ơn, tôi thực sự thích giải pháp của bạn. – Sharique

Các vấn đề liên quan