Requirement: a previous console program, because the command line method is not user-friendly, adds an interface to call the console program, but the previous console output information will be redirected to the new interface, otherwise, it is worse if the user does not know the program information.
Redirection under the command line is easy (Hello> 1.txt, Linux | pipeline is more powerful), but it is not so easy to call redirection in. net.
First, write an example program, a form program, and a button in it. Each time a button is clicked, there are some items in console. writeline.
Private void hellobtn_click (Object sender, eventargs E)
...{
Console. writeline (++ num );
}
Write another program and call hello.exe.direct the hello.exe command line output to the textbox.
Private delegate void appendrichtext (string Str );
Public redirectform ()
...{
Initializecomponent ();
}
Private void redirectform_load (Object sender, eventargs E)
...{
Thread t = new thread (New threadstart (printtext ));
T. Start ();
}
Private void printtext ()
...{
PROCESS p = new process ();
P. startinfo = new processstartinfo ();
P. startinfo. filename = "hello ";
P. startinfo. redirectstandardoutput = true;
P. startinfo. useshellexecute = false;
P. Start ();
Streamreader reader = P. standardoutput; // captures the output stream
String input = reader. Readline (); // read a row each time
While (! Reader. endofstream)
...{
// Redirect the output to textbox
This. Invoke (New appendrichtext (appendtext), input); // The Problem of winform multithreading is that the form control attributes cannot be changed in other threads (except for a few attributes)
Input = reader. Readline ();
}
P. waitforexit ();
}
Private void appendtext (string text)
...{
This. richtextbox1.appendtext (Text + "");
}
In this way, information can be transmitted between processes.