【问题标题】:vb.net cmd shell result is not coming untill cmd is closevb.net cmd shell 结果在 cmd 关闭之前不会出现
【发布时间】: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

【问题讨论】:

标签: .net vb.net


【解决方案1】:

ReadToEnd 方法并不意味着“读取当前可用的任何内容”。它的意思是“读到流的末尾”。这意味着在流结束之前你不会得到任何回报。这就像对Console.ReadLine 的调用在有整行要读取之前不会返回。如果您想以块的形式获取输出,那么您必须调用一个获取块的方法并重复执行此操作,直到没有更多块为止。显而易见的选项似乎是 ReadLine,但这取决于您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 2020-06-02
    • 2019-01-13
    • 2018-04-03
    • 2010-12-04
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多