System.Diagnostics.Process
FileName
Arguments
Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = FileName; process.StartInfo.Arguments = Arguments; process.StartInfo.WorkingDirectory = WorkingDirectory; process.Start();
StreamReaders
Process.StandardOutput
Process.StandardError
string output = process.StandardOutput.ReadToEnd();
void ReadStdOut() { string str; while ((str = process.StandardOutput.ReadLine()) != null) { // do something with str } }
Control.Invoke
Control.BeginInvoke
public delegate void DataReceivedHandler(object sender, DataReceivedEventArgs e); public event DataReceivedHandler StdOutReceived; void ReadStdOut() { string str; while ((str = process.StandardOutput.ReadLine()) != null) { FireAsync(StdOutReceived, this, new DataReceivedEventArgs(str)); } }
FireAsync
AsyncOperation
StdOutReceived
DataReceivedEventArgs
EventArgs
Start()
Cancel()
DoWork()
CancelRequested
void protected override void DoWork()() { // Start a new process for the cmd Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = FileName; process.StartInfo.Arguments = Arguments; process.StartInfo.WorkingDirectory = WorkingDirectory; process.Start(); // Invoke stdOut and stdErr readers - each // has its own thread to guarantee that they aren't // blocked by, or cause a block to, the actual // process running (or the gui). new MethodInvoker(ReadStdOut).BeginInvoke(null, null); new MethodInvoker(ReadStdErr).BeginInvoke(null, null); // Wait for the process to end, or cancel it while (! process.HasExited) { Thread.Sleep(SleepTime); // sleep if (CancelRequested) { // Not a very nice way to end a process, // but effective. process.Kill(); AcknowledgeCancel(); } } }
ReadStdOut()
ReadStdErr()
StdErrReceived
StdOutRecieved
private void writeStreamInfo(object sender, DataReceivedEventArgs e) { this.richTextBox1.AppendText(e.Text + Environment.NewLine); }
ProcessCaller
没有评论:
发表评论