Many professional configuration tools do not provide UI tools, but only command line operations, such as the configuration of many network facilities. The command line tool has the advantages of high input efficiency and batch operation. However, it has high professional requirements for users, and a large amount of command input is also a test of memory.
In fact, we can use. Net to visualize some common commands, which is convenient to use and reduces the burden of inputting a large number of commands.
We mainly use the system. Diagnostics. process and system. Diagnostics. processstartinfo classes.
Create a simple WPF form that contains two text boxes to display the input and output information. Then, add several command buttons to register the button Event Response:
VaR runprocess = new process (); string cmd = "Ping 10.10.10.2"; var Config = new processstartinfo ("cmd.exe"); // The Program executed, which is the cmd.exe command line tool config. redirectstandardinput = true; // redirect the input stream of the command line, so that we can input commands through the program to simulate manual input of config. redirectstandardoutput = true; // The output stream is redirected to ensure that the output result config is obtained after the command is executed by the command line. useshellexecute = false; // the command line running window is not displayed? Config. createnowindow = true; // The runprocess window of the command line is not displayed. startinfo = config; runprocess. outputdatareceived + = runprocess_outputdatareceived; // register the output stream event. Once the command line outputs information, runprocess can be retrieved. start (); runprocess. standardinput. writeline (CMD); // enter various control commands runprocess. beginoutputreadline (); // starts to read output information. This is a key step; otherwise, no output event is triggered.
Next, a simple event subscription is output:
void runProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) { Dispatcher.BeginInvoke(new Action(() => output.Text += e.Data)); }
We can see that the output string is only obtained from data in datareceivedeventargs. Note that the event execution program runs in other threads. In sta programs such as winform and WPF, messages must be sent to the UI thread. dispatcher is used in WPF. invoke (Action) method.
, Running effect. In this way, we can encapsulate a lot of Common commands to the graphic interface for non-professional users to use.
Graphical command line tool: