问题
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);
}
回答1:
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.
回答2:
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.
回答3:
You may wish to consider reversing the logic, ie. close the already running instance and re-launch with your new parameters.
回答4:
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.
来源:https://stackoverflow.com/questions/4541354/simple-communication-between-2-instances-of-application