C # The redirection process calls winform Multithreading

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.