【发布时间】:2017-04-21 07:02:19
【问题描述】:
我正在尝试编写一个简单的 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
结束类
【问题讨论】:
标签: .net vb.net process io-redirection