【发布时间】:2020-04-18 11:02:00
【问题描述】:
有 2 个文本框和 1 个按钮
button1 = 启动 cmd 进程
textbox1 = 键入要在 cmd 上运行的命令
textbox2 = cmd 进程的实时结果
在这种情况下,我将 textbox1 替换为“ping www.google.com”和“ping www.facebook.com”
问题是.. 直到 cmd 关闭才会出现结果
cmd不是自动关闭的..我必须自己关闭它
这是我的代码
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Threading
Imports System.Windows
Public Class Form1
Private Results As String
Private Delegate Sub delUpdate()
Private Finished As New delUpdate(AddressOf UpdateText)
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
StartInfo.FileName = "cmd"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False
StartInfo.CreateNoWindow = False
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
myprocess.StandardInput.WriteLine("ping www.google.com")
myprocess.StandardInput.WriteLine("ping www.facebook.com")
End Sub
Private Sub CMDAutomate()
On Error Resume Next
While myprocess.StandardOutput.EndOfStream = False
Results = myprocess.StandardOutput.ReadToEnd.ToString()
Invoke(Finished)
End While
End Sub
Private Sub UpdateText()
TextBox2.AppendText(System.Environment.NewLine() & Results)
TextBox2.ScrollToCaret()
End Sub
End Class
【问题讨论】:
-
How do I get output from a command to appear in a control on a Form in real-time?。阅读那里的笔记。顺便说一句,当您设置
SynchronizingObject时,不需要所有 BeginInvoke() 调用。它用于测试是否存在差异(剧透警告:没有)。