1

我正在尝试重定向由我的应用程序启动的第三方命令行工具的输出。我正在输出到富文本框。这是成功的,但有一个例外。

当我使用 ping 命令进行测试时,我的输出格式不正确。一行附加到前一行。当我尝试在VbNewLine其中放置 a 或 aVbCrLf或 a时Environment.NewLine,会放置一个额外的空白行。

我得到这个输出:

Pinging 8.8.8.8 with 32 bytes of data:



Reply from 8.8.8.8: bytes=32 time=29ms TTL=44

Reply from 8.8.8.8: bytes=32 time=29ms TTL=44

Reply from 8.8.8.8: bytes=32 time=30ms TTL=44

Reply from 8.8.8.8: bytes=32 time=29ms TTL=44




Ping statistics for 8.8.8.8:

    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

    Minimum = 29ms, Maximum = 30ms, Average = 29ms

我想得到(因为它在 CMD 窗口中):

Pinging 8.8.8.8 with 32 bytes of data:

Reply from 8.8.8.8: bytes=32 time=31ms TTL=44
Reply from 8.8.8.8: bytes=32 time=29ms TTL=44
Reply from 8.8.8.8: bytes=32 time=29ms TTL=44
Reply from 8.8.8.8: bytes=32 time=29ms TTL=44

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

我敢肯定这很简单,但无法弄清楚。

这是我正在使用的代码。

Private Sub StartProcess()

    Dim Proc = New Process()

    Proc.StartInfo.FileName = "ping"
    Proc.StartInfo.Arguments = "8.8.8.8"

    Proc.StartInfo.RedirectStandardOutput = True
    Proc.StartInfo.RedirectStandardError = True
    Proc.EnableRaisingEvents = True
    Application.DoEvents()
    Proc.StartInfo.CreateNoWindow = True
    Proc.StartInfo.UseShellExecute = False

    AddHandler Proc.ErrorDataReceived, AddressOf proc_OutputDataReceived
    AddHandler Proc.OutputDataReceived, AddressOf proc_OutputDataReceived
    Proc.Start()
    Proc.BeginErrorReadLine()
    Proc.BeginOutputReadLine()
    'Proc.WaitForExit()

End Sub


Delegate Sub UpdateTextBoxDelg(ByVal text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)

Public Sub UpdateTextBox(ByVal text As String)
    box_output.AppendText(text)
End Sub

Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    On Error Resume Next
    If Me.InvokeRequired = True Then
        Me.Invoke(myDelegate, e.Data)
    Else
        UpdateTextBox(e.Data)
    End If

End Sub
4

2 回答 2

3

有点笨拙,花了我一段时间。我注意到 e.Data 可以是 Nothing,以前从未见过。网络公用事业是,呃,特别,伯克利是地球上一个不寻常的地方。

您必须自己添加行尾。使用 InvokeRequired 毫无意义,它始终用于 OutputDataReceived 事件。这个版本运行良好:

Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    If e.Data IsNot Nothing Then Me.Invoke(myDelegate, e.Data + vbCrLf)
End Sub

请改用 System.Net.NetworkInformation.Ping 类。它不受娱乐性化学物质的影响。

于 2013-11-06T23:04:24.977 回答
0

它对我来说工作正常;只需按如下方式修改您的代码:

Public Sub UpdateTextBox(ByVal text As String)
    RichTextBox2.AppendText(text & System.Environment.NewLine)
End Sub

截屏

于 2017-08-08T06:13:29.017 回答