使用VB.net读取和写入命令提示符控制台 [英] Reading and writing to a command prompt console using VB.net

查看:221
本文介绍了使用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.

我想得到:


  1. 打开Windows命令提示符

  2. 通过dos运行DOS应用程序命令

  3. 读取dos框中显示的返回文本,并将其显示在Windows窗体的文本框中。需要定期(例如,每秒)重复一次,并且不要关闭dos框。

我一直在尝试使用Process和StartInfo命令绕圈,但是它们仅运行应用程序并立即关闭进程。我需要保持dos框处于打开状态,并继续阅读dos应用程序添加到它的任何新文本。我还遇到了这个似乎可以解决我问题的线程,但这是在C#中,并且我无法将其转换:

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:

阅读Windows命令提示符STDOUT

到我打开命令提示符并启动应用程序的那一部分,但是我不知道如何不时读取它返回到dos box控制台的数据。我想不断检查是否有更改,以便可以使用计时器控件对它们进行操作。

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.

请帮助。

谢谢!

我运行了Stevedog提供的代码,并像这样使用它:

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~2\zbar\bin\zbarcam.exe", "")
  End Sub

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

但是我得到的只是空白的剂量盒。 zbarcam应用程序可以正常运行,因为我可以看到相机预览,也可以看到它检测到QR码,但是该文本未显示在dos框中,并且 _commandExecutor_OutputRead 子项未显示除非我关闭DOS框,否则将被触发。

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.

推荐答案

该C#示例很糟糕,因为它没有显示如何实际读取标准输出流。创建这样的方法:

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当然这会进行同步呼叫。如果您希望它异步调用命令行,并在完成时引发一个事件,这也是可能的,但是需要更多的编码。

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:\Sandbox\SandboxSolution\ConsoleCs\bin\Debug\ConsoleCs.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

这篇关于使用VB.net读取和写入命令提示符控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆