문제

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);
}
도움이 되었습니까?

해결책

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.

다른 팁

Why don't you just send a Windows message in the WM_USER range. You'll need to do a bit of marshalling of the information but you can do that with GlobalAlloc, GlobalLock, etc. quite easily.

You may wish to consider reversing the logic, ie. close the already running instance and re-launch with your new parameters.

If you're using .net 4, you might consider memory mapped files for inter-process communication. The second instance could write some data to shared memory, set a system mutex to notify the original instance, then shut-down. See this overview of memory mapped files.

Or, simpler yet, write the command line arguments to a simple text file in a folder that is always monitored by the original instance. The original instances sees the new file, processes it, then deletes it. This approach works with any version of .net and would be easier to test/debug.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top