在列表框中显示命令提示符中显示的消息

时间:2011-08-07 11:51:52

标签: c# vb.net dos message command-prompt

实际上我想显示cmd提示中显示的消息,如果我这样做:

Ping google.com -t

cmd提示符中将显示以下消息:

Reply from 74.125.235.17: bytes=32 time=133ms TTL=51
Reply from 74.125.235.17: bytes=32 time=130ms TTL=51
Reply from 74.125.235.17: bytes=32 time=130ms TTL=51
Reply from 74.125.235.17: bytes=32 time=130ms TTL=51

Ping statistics for 74.125.235.17:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 130ms, Maximum = 133ms, Average = 130ms

我希望在完成整个过程后,在命令提示符中显示时,立即在程序的列表框中显示确切的信息。我怎么能这样做?有帮助吗?我正在使用C#/ vb.net。

ping google.com -t 一样,我想在列表框中立即显示每条回复消息。

3 个答案:

答案 0 :(得分:2)

为此,您需要使用async read on standardoutput ...另请参阅this ...

Here你可以找到所描述问题的解决方案,包括源代码......它甚至考虑了stderr ......

其他有趣的资源:

答案 1 :(得分:1)

试试这个:

Private Results As String

'The "Delegate" is used to correct the threading issue (Can't update control directly in VB.net 08/10), and invokes the needed text update.
Private Delegate Sub delUpdate()
Private Finished As New delUpdate(AddressOf UpdateText)

Private Sub UpdateText()
resultsTextBox.Text = Results
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
End Sub

Private Sub CMDAutomate()

Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo

'Starts the CMD Prompt
StartInfo.FileName = "cmd.exe"
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True

'Required to redirect
StartInfo.UseShellExecute = False

'Disables the creation of a CMD Prompt outside application.
StartInfo.CreateNoWindow = True


myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput

'Runs the command you entered...
SW.WriteLine(TextBox1.Text)

'Exits CMD Prompt 
SW.WriteLine("exit")

'Displayes the results...
Results = SR.ReadToEnd
SW.Close()
SR.Close()

'Invokes Finished delegate, which updates textbox with the results text
Invoke(Finished)
End Sub

答案 2 :(得分:0)

快速解决方案。

  • 将输出重定向到C:\ ping.txt

    “Ping google.com -t> C:\ ping.txt”

  • 每隔x秒读取ping.txt

    File.ReadAllText( “C:\ ping.txt”)

  • 在UI安全线程中更新ListBox参考

    How to update the GUI from another thread in C#?