问题
I have a WPF application and I need to spin up a separate MFC application and then communicate with it. I was going to use Process.Start
, but I'm wondering if there is a better way to do this these days. I can research things myself, but I need to know where to start. Thanks.
Edits:
I found this suggesting there isn't. Is this true?
Alternatives to System.Diagnostics.Process.Start()
Thanks.
回答1:
For your immediate question, there is nothing new in the recent versions of .NET that gives a better or more up-to-date way to start a local executable. Process.Start is (and has been) the way to go.
The simplest, and most convenient, is to select one of the five static methods on Process. Passing strings or a populated StartInfo instance. You would use the latter if you needed more control over how the process got raised. Or of interest in your case, if you wanted to pipe the program's stdio as a stream into your own application. Here's a sample of populating a Start Info instance from one of my utilities...
ProcessStartInfo start = new ProcessStartInfo(BaseIoConstantsProvider.CommandProcessor)
{
Arguments = BaseIoConstantsProvider.KeepAlive,
UseShellExecute = false,
CreateNoWindow = BaseIoConstantsProvider.NoDosWindow,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
For the second part of your question, the static method will not do if you need to interact with the process once it is started. From the same utility...
Process p = new Process { StartInfo = start, EnableRaisingEvents = true };
p.ErrorDataReceived += PErrorDataReceived;
p.Exited += PExited;
p.Start();
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(cmdLine);
p.BeginOutputReadLine();
This example shows a two events being hooked along with reading the stdio from the process. It's great for that purpose, but overkill if you just want to start another executable.
So the main determinate in selecting a start method is the question: does my app need to interact with the process once it's started?
And finally, sometimes you may want to invoke a canonical verb, or even create a verb of your own to start a given process. These appear in the context menu when you right click an item and give you lots of additional flexibility for starting a process. There's an excellent article here http://msdn.microsoft.com/en-us/library/windows/desktop/cc144101(v=vs.85).aspx#canonical on how to implement a verb.
来源:https://stackoverflow.com/questions/18338397/start-and-manage-external-process-from-a-wpf-app