0
我正在嘗試編寫一個簡單的vb程序來將標準輸入/輸出同步到一個文本框。程序首先應該找到一個exe文件,然後運行該文件並輸出到文本框,然後關閉該文件,然後重新運行該文件或運行其他文件。第一次事情會很好,但是當我關閉文件並嘗試重新運行時,我無法再獲得輸出。請讓我知道什麼是錯的。下面的代碼:打開一個進程,獲取輸出,然後打開另一個進程並獲得輸出
Public Class Form1
Dim P As New Process
Dim SW As System.IO.StreamWriter
Dim fd As New OpenFileDialog
Dim progName As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
P.StartInfo.CreateNoWindow = False
P.StartInfo.UseShellExecute = False
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.SynchronizingObject = TextBox1
fd.Title = "Open Program"
fd.InitialDirectory = "C:\windows\system32"
fd.Filter = "EXE program | *.exe"
fd.FilterIndex = 1
fd.RestoreDirectory = True
End Sub
Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
TextBox1.AppendText(output.Data() & vbCrLf)
End Sub
Private Sub Textbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Static Line As String
If e.KeyChar = Chr(Keys.Return) Then
SW.WriteLine(Line & vbCrLf)
Line = ""
Else
Line = Line & e.KeyChar
End If
End Sub
Private Sub OpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenFile.Click
If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
progName = fd.FileName
TextBox1.AppendText(progName & vbCrLf)
End If
End Sub
Private Sub ButtonRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRun.Click
ButtonRun.Enabled = False
ButtonStop.Enabled = True
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
AddHandler P.ErrorDataReceived, AddressOf DisplayOutput
P.StartInfo.FileName = progName
P.Start()
P.BeginOutputReadLine()
SW = P.StandardInput
SW.WriteLine()
End Sub
Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonStop.Click
ButtonStop.Enabled = False
ButtonRun.Enabled = True
P.CancelOutputRead()
RemoveHandler P.OutputDataReceived, AddressOf DisplayOutput
RemoveHandler P.ErrorDataReceived, AddressOf DisplayOutput
''P.CloseMainWindow()
P.Close()
End Sub
末級
中提琴!現在完美!謝謝德米特里!週末愉快。 – Heibear