Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

windows - Reading and writing to a command prompt console using VB.net

I have asked a similar question elsewhere but perhaps I did not ask it the right way or I was not clear enough so I am asking again.

This is where I want to get:

  1. Open a windows command prompt
  2. Run a DOS application through a dos command
  3. Read the returned text that is shown in the dos box and show it in a text box in my windows form. This needs to be repeated at regular intervals (say, every second) and the dos box should not be closed.

I have been going round in circles trying to use the Process and StartInfo commands, but they only run the application and close the process right away. I need to keep the dos box open and keep reading any new text that is added to it by the dos application. I also came across this thread that seems to answer my problem, but it is to in C# and I could not convert it:

Read Windows Command Prompt STDOUT

I did get to the part where I open the command prompt and get the application started, but I don't know how to read the data that it returns to the dos box console every now and then. I want to constantly check for changes so that I can act on them, perhaps using a timer control.

Please help.

Thanks!

I ran the code that was kindly provided by Stevedog and used it like this:

  Private WithEvents _commandExecutor As New CommandExecutor()

  Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    _commandExecutor.Execute("c:progra~2zbarinzbarcam.exe", "")
  End Sub

  Private Sub _commandExecutor_OutputRead(ByVal output As String) Handles _commandExecutor.OutputRead
    txtResult.Text = output
  End Sub

But all I am getting is blank dos box. The zbarcam application runs properly because I can see the camera preview and I can also see it detecting QR Codes, but the text is not showing in the dos box and _commandExecutor_OutputRead sub is not being triggered unless I close the DOS box.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That C# example is bad because it doesn't show how to actually read the standard output stream. Create a method like this:

Public Function ExecuteCommand(ByVal filePath As String, ByVal arguments As String) As String
    Dim p As Process
    p = New Process()
    p.StartInfo.FileName = filePath
    p.StartInfo.UseShellExecute = False
    p.StartInfo.RedirectStandardInput = True
    p.StartInfo.RedirectStandardOutput = True
    p.Start()
    p.WaitForExit()
    Return p.StandardOutput.ReadToEnd()
End Function

Then you can call it like this:

Dim output As String = ExecuteCommand("mycommand.exe", "")

Of course this makes a synchronous call. If you want it to call the command line asynchronously and just raise an event when it's complete, that is possible too, but would require a little more coding.

If you want to do it asynchronously and just keep periodically checking for more output on a fixed interval, for instance, here's a simple example:

Public Class CommandExecutor
    Implements IDisposable

    Public Event OutputRead(ByVal output As String)

    Private WithEvents _process As Process

    Public Sub Execute(ByVal filePath As String, ByVal arguments As String)
        If _process IsNot Nothing Then
            Throw New Exception("Already watching process")
        End If
        _process = New Process()
        _process.StartInfo.FileName = filePath
        _process.StartInfo.UseShellExecute = False
        _process.StartInfo.RedirectStandardInput = True
        _process.StartInfo.RedirectStandardOutput = True
        _process.Start()
        _process.BeginOutputReadLine()
    End Sub

    Private Sub _process_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles _process.OutputDataReceived
        If _process.HasExited Then
            _process.Dispose()
            _process = Nothing
        End If
        RaiseEvent OutputRead(e.Data)
    End Sub

    Private disposedValue As Boolean = False
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                If _process IsNot Nothing Then
                    _process.Kill()
                    _process.Dispose()
                    _process = Nothing
                End If
            End If
        End If
        Me.disposedValue = True
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
End Class

Then you could use it like this:

Public Class Form1
    Private WithEvents _commandExecutor As New CommandExecutor()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        _commandExecutor.Execute("D:SandboxSandboxSolutionConsoleCsinDebugConsoleCs.exe", "")
    End Sub

    Private Sub _commandExecutor_OutputRead(ByVal output As String) Handles _commandExecutor.OutputRead
        Me.Invoke(New processCommandOutputDelegate(AddressOf processCommandOutput), output)
    End Sub

    Private Delegate Sub processCommandOutputDelegate(ByVal output As String)
    Private Sub processCommandOutput(ByVal output As String)
        TextBox1.Text = output
    End Sub

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        _commandExecutor.Dispose()
    End Sub
End Class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...