0

All, I am trying to prevent multiple instances of an app, What I want to do is closing the last process, and running a new process for the app. Currently I knew I can stop running multiple instances for a winform application like this post. But I want to know how to close the last one safely. I don't want to use the Process.kill method to terminate the app. I want to close it safely. So far I think the code should look like below . please help to review it .thanks.

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         //close the last one. 
         //......I don't know how to make it.  
      }

      Application.Run(new Form1());
   }
}

private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
Community
  • 1
  • 1
Joe.wang
  • 11,537
  • 25
  • 103
  • 180
  • 1
    Why are you closing last one? Simply don't start new one – Sergey Berezovskiy Oct 31 '13 at 08:22
  • @lazyberezovsky Because the app have some start up parameters , maybe they are different every times when the app starts up. so , What I want to do is running the app with the new parameters , If don't start new one, you know , the parameter for the app is old. not the ones I want to use. thanks. – Joe.wang Oct 31 '13 at 08:27
  • You can pass parameters to already running instance – Sergey Berezovskiy Oct 31 '13 at 08:30
  • Could you please tell me how to pass the new parameters to already running instance? thanks. – Joe.wang Oct 31 '13 at 08:33
  • I think you need some kind of IPC (Inter-Process Communication). I usually use WCF which is quite easy for such a goal. – nim Oct 31 '13 at 09:07
  • 5
    It is a built-in .NET feature, use the WindowsFormsApplicationBase class. Set its IsSingleInstance property to true, use the StartupNextInstance event to know what arguments were used for the 2nd instance. Sample code [is here](http://stackoverflow.com/questions/11923785/run-one-instance-of-program/11923963#11923963) – Hans Passant Oct 31 '13 at 10:06
  • @HansPassant, years ago I wrote my own code to do this leveraging the Windows API to check the title of the window (man how I've grown); but I still didn't know about this. Thanks a lot friend, that will save me later in life I'm sure! – Mike Perrenoud Oct 31 '13 at 12:37

0 Answers0