为此添加三个文本框
1) txterror(从命令提示符或 DOS 获取错误)
2) txtresult(从命令提示符或 DOS 获取结果)
3)txtcommand(写DOS命令执行)
在表单加载中编写以下代码
' Set start information.
Dim start_info As New ProcessStartInfo("cmd")
start_info.UseShellExecute = False
start_info.CreateNoWindow = True
start_info.RedirectStandardOutput = True
start_info.RedirectStandardError = True
start_info.RedirectStandardInput = True
' Make the process and set its start information.
Dim proc As New Process()
proc.StartInfo = start_info
' Start the process.
proc.Start()
' Attach to stdout and stderr.
Dim std_out As StreamReader = proc.StandardOutput()
Dim SW As System.IO.StreamWriter = proc.StandardInput
Dim std_err As StreamReader = proc.StandardError()
SW.WriteLine(txtcommand.Text)
SW.WriteLine("exit")
' Display the results.
txtresult.Text = std_out.ReadToEnd()
' Clean up.
std_out.Close()
std_err.Close()
proc.Close()
在文本框 keydown 事件中编写以下代码(即 txtcommand_KeyDown)
If e.KeyCode = Keys.Enter Then
txterror.Text = ""
' Set start information.
Dim start_info As New ProcessStartInfo("cmd")
start_info.UseShellExecute = False
start_info.CreateNoWindow = True
start_info.RedirectStandardOutput = True
start_info.RedirectStandardError = True
start_info.RedirectStandardInput = True
' Make the process and set its start information.
Dim proc As New Process()
proc.StartInfo = start_info
' Start the process.
proc.Start()
' Attach to stdout and stderr.
Dim std_out As StreamReader = proc.StandardOutput
Dim SW As System.IO.StreamWriter = proc.StandardInput
Dim std_err As StreamReader = proc.StandardError()
SW.WriteLine(txtcommand.Text)
SW.WriteLine("exit")
' Display the results.
txtresult.Text = std_out.ReadToEnd()
txterror.Text = std_err.ReadToEnd()
std_err.Dispose()
SW.Close()
' Clean up.
std_out.Close()
std_err.Close()
proc.Close()
End If