2008-09-09 5 views
7

सी # विंडोज फॉर्म एप्लिकेशन में मैं यह जानना चाहता हूं कि एप्लिकेशन का एक और उदाहरण पहले से चल रहा है या नहीं। यदि ऐसा है, तो चल रहे इंस्टेंस के मुख्य रूप को सक्रिय करें और इस उदाहरण से बाहर निकलें।एक इंस्टेंस एप्लिकेशन के मुख्य रूप को सक्रिय करना

इसे प्राप्त करने का सबसे अच्छा तरीका क्या है?

उत्तर

8

स्कॉट हंसेलमैन answers विवरण पर आप प्रश्न पूछते हैं।

4

यहां मैं एप्लिकेशन की प्रोग्राम.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

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

 संबंधित मुद्दे

  • कोई संबंधित समस्या नहीं^_^