2015-08-14 5 views
-1

Я хочу убедиться, что работает только один экземпляр моего приложения winform. Есть ли способ, что я могу достигнуть его через Visual Studio 2008, а не делать это в коде позадиУбедитесь, что только один экземпляр приложения winform запущен

+1

Это является встроенной функцией VB.NET. Если вы используете другой язык, вам придется написать несколько строк кода. –

ответ

0

статической силы Main() {

 if (PriorProcess() != null) 
     { 

      MessageBox.Show("Another instance of the app is already running."); 
      return; 
     } 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     Application.Run(new Form1()); 


    } 

    public static Process PriorProcess() 
    // Returns a System.Diagnostics.Process pointing to 
    // a pre-existing process with the same name as the 
    // current one, if any; or null if the current process 
    // is unique. 
    { 
     Process curr = Process.GetCurrentProcess(); 
     Process[] procs = Process.GetProcessesByName(curr.ProcessName); 
     foreach (Process p in procs) 
     { 
      if ((p.Id != curr.Id) && 
       (p.MainModule.FileName == curr.MainModule.FileName)) 
       return p; 
     } 
     return null; 
    } 
1

в C# вы можете сделать что-то подобное в вашем Program.cs

static class Program 
{ 
    public static FormMain MainForm = null; 

    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE80}"); 
    [STAThread] 
    static void Main() 
    { 
     if (mutex.WaitOne(TimeSpan.Zero, true)) 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      MainForm = new FormMain(); 
      Application.Run(MainForm); 
      mutex.ReleaseMutex(); 
     } 
     else 
     { 
      // send our Win32 message to make the currently running instance 
      // jump on top of all the other windows 
      NativeMethods.PostMessage(
       (IntPtr)NativeMethods.HWND_BROADCAST, 
       NativeMethods.WM_SHOWME, 
       IntPtr.Zero, 
       IntPtr.Zero); 

     } 
    } 
} 

и в вашем MainForm поставить этот

protected override void WndProc(ref Message m) 
    { 
     if (m.Msg == NativeMethods.WM_SHOWME) 
     { 
      ShowMe(); 
     } 
     base.WndProc(ref m); 
    } 

    private void ShowMe() 
    { 
     if (WindowState == FormWindowState.Minimized) 
     { 
      WindowState = FormWindowState.Normal; 
     } 
     // get our current "TopMost" value (ours will always be false though) 
     bool top = TopMost; 
     // make our form jump to the top of everything 
     TopMost = true; 
     // set it back to whatever it was 
     TopMost = top; 
    } 
+0

У меня есть решение. благодаря –

Смежные вопросы