从CMD控制台到VB ListBox的流输出

时间:2014-06-14 11:41:31

标签: vb.net visual-studio-2010 visual-studio

我试图逐行将文本从控制台传递到Listbox1,因此隐藏的控制台会将其输出流式传输到我的ListBox。但是我得到了Cross-thread operation not valid

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim start_info As New ProcessStartInfo()

    start_info.FileName = ("cmd.exe")
    start_info.UseShellExecute = False
    start_info.CreateNoWindow = False
    start_info.RedirectStandardOutput = True
    start_info.WindowStyle = ProcessWindowStyle.Hidden
    start_info.Arguments = ("ipconfig")

    Dim proc As New Process
    proc.StartInfo = start_info
    proc.Start()

    Dim std_out As System.IO.StreamReader
    std_out = proc.StandardOutput

    Do
        ListBox1.Items.Add(std_out.ReadLine)
    Loop While proc.HasExited = False

End Sub

1 个答案:

答案 0 :(得分:2)

DoWork的{​​{1}}事件在与UI不同的线程中运行。您必须确保在UI线程中添加了Items。例如,使用BackgroundWorker来完成此任务。

将您的Invoke更改为以下内容:

Do ... Loop While

有关MSDN的更多信息: