Search code examples
c#communicationsingle-instance

Simple Communication between 2 instances of application


I have a WPF application that can take a few optional command line arguments.

This application is also a single instance application (using a mutex to close any instances if one is already open).

What I want for it to do though, is if something tries to open the application with some cmd line args, that the application will do what it's suppose to do with those (in my application it opens different dialogs based on the cmd line).

What is the easiest way to achieve this?

In psedo code here is what i'm looking for

protected override void OnStartup(StartupEventArgs e)
{
     bool mutexIsNew;
     using (System.Threading.Mutex m = 
            new System.Threading.Mutex(true, "MyApplication", out mutexIsNew))
     {
         //if this is not the first instance of the app
         if (!mutexIsNew)
         {
              //if there is some cmd line args  
              if (e.Args.Length > 0)
              {
                   //send the args to the older instance so it can handle them
                   SendToOtherInstance(e.Args);
                   //shutdown this new instance
                   Application.Current.Shutdown();
               }

         }
     }
     base.OnStartup(e);
}

Solution

  • There are lots of implementations of single instance apps on Code Project, actually there are so many of them it's hard to decide which one you want...

    I tried several solutions, and I really like this one. It makes it very easy to intercept command line parameters passed to the second instance.