【问题标题】:Displaying message shown in command prompt in list box在列表框中显示命令提示符中显示的消息
【发布时间】:2011-08-07 11:51:51
【问题描述】:

实际上我想显示 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 中一样,我想在列表框中立即显示每条回复消息。

【问题讨论】:

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


    【解决方案1】:

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

    Here你可以找到一个完整的源代码解决方案......它甚至考虑到stderr......

    其他有趣的资源:

    【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    【讨论】:

    • 提到您需要一个名为 resultsTextBox 的 tex 框和一个名为 Button1 的按钮
    • 这是输出,还有一些额外的行,你可以删除它们i.stack.imgur.com/RByCO.png
    • 您上面的代码可以工作,但在所有工作完成后它会在列表框中显示结果。但我想立即显示消息,即在 ping google.com -t; 的情况下我想在列表框中立即显示每条回复消息。
    • 嗯,也许你必须处理 SR。
    【解决方案3】:

    为您提供快速解决方案。

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多