在VB	 10中运行基于Java控制台的程序

时间:2014-01-26 17:44:51

标签: vb.net

我基本上试图以某种方式在vb.net中运行一个基于java控制台的程序并显示输出,让我们说一个普通的文本框,还有另一个文本框,我可以在其中键入输入到程序。有可能这样做吗?

2 个答案:

答案 0 :(得分:1)

您基本上需要使用参数创建一个新进程,该进程将是文本框的输入。然后,您可以捕获程序的输出,将其存储在变量中并在对话框中显示它。

这是一个小片段:

Dim command As String = "C:\My Dir\MyFile.exe"
Dim args As String = "MyParam1 MyParam2"

Dim proc = New Process() With { _
  Key .StartInfo = New ProcessStartInfo() With { _
    Key .FileName = "program.exe", _
    Key .Arguments = args, _
    Key .UseShellExecute = False, _
    Key .RedirectStandardOutput = True, _
    Key .CreateNoWindow = True _
  } _
}

proc.Start()

While Not proc.StandardOutput.EndOfStream
  Dim line As String = proc.StandardOutput.ReadLine()
  ' do something with the line
End While

答案 1 :(得分:0)

以下是一些样板代码(确保表单上有txtInputtxtOutput):

Private m_process As Process
Private m_encoding_for_program As System.Text.Encoding

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    m_encoding_for_program = System.Text.Encoding.GetEncoding(866) 'Adjust as needed

    Dim psi As New ProcessStartInfo
    psi.CreateNoWindow = True
    psi.UseShellExecute = False
    psi.FileName = "cmd.exe"
    psi.RedirectStandardInput = True
    psi.RedirectStandardError = True
    psi.StandardErrorEncoding = m_encoding_for_program
    psi.RedirectStandardOutput = True
    psi.StandardOutputEncoding = m_encoding_for_program

    m_process = Process.Start(psi)
    AddHandler m_process.OutputDataReceived, AddressOf OutputDataReceived
    AddHandler m_process.ErrorDataReceived, AddressOf OutputDataReceived 'Make different handler if needed.
    m_process.BeginOutputReadLine()
    m_process.BeginErrorReadLine()

End Sub

Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
    m_process.CancelOutputRead()
    m_process.CancelErrorRead()
    m_process.Kill()
End Sub

Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInput.KeyUp
    If e.KeyCode = Keys.Enter Then
        Dim b = m_encoding_for_program.GetBytes(txtInput.Text)
        m_process.StandardInput.BaseStream.Write(b, 0, b.Length)
        m_process.StandardInput.WriteLine()
    End If
End Sub

Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    Me.Invoke(CType(AddressOf Me.ThreadProcSetter, Action(Of Object)), e.Data)
End Sub

Private Sub ThreadProcSetter(ByVal text As Object)
    txtOutput.AppendText(DirectCast(text, String) & ControlChars.NewLine)
End Sub

txtInput中输入命令,然后按Enter键查看结果。确保txtOutput是多行的 根据需要添加错误检查。