Home > OS >  How to display output of cmd commands in a TextBox
How to display output of cmd commands in a TextBox

Time:07-20

I'm trying to find a working example of some vb code to issue commands like dir or ping or other cmd commands and display their output in a forms textbox. I found several old examples online, but none of the seem to work in my VB Express 2017 environment. Older examples were automatically converted during opening, but don't work either... Has anybody seen a working version? Thank you very much in advance!

Kind regards, Eric

CodePudding user response:

Well, you can adopt some existing code. (not a bad idea). However, a lot of examples have all kinds of fancy async code, event code. There is HUGE and MASSIVE reason for 50 years, that hello world programs still exist!!!

They allow people starting out to learn.

So, I suggest you drop in a text box, a button, and then a LARGER multi-line text box.

Say like this form

enter image description here

So, we can enter a command prompt. When we hit run command, it will run that command, and capture the out put.

Code behind that button is this:

Private Sub cmdMyShell_Click(sender As Object, e As EventArgs) Handles cmdMyShell.Click

    Dim MyProcess As New Process
    MyProcess.StartInfo.FileName = "cmd.exe"
    MyProcess.StartInfo.Arguments = " /C" & TextBox1.Text

    MyProcess.StartInfo.UseShellExecute = False
    MyProcess.StartInfo.RedirectStandardOutput = True
    MyProcess.Start()

    ' get the output
    Dim strMyBuffer As String = ""

    strMyBuffer = MyProcess.StandardOutput.ReadToEnd
    MyProcess.WaitForExit()

    ' now display this output in the text box:
    TextBox2.Text = strMyBuffer

End Sub

Ok, so when I run above, get this:

enter image description here

Or, how about say ipconfig.

enter image description here

So, the above is a really simple bit of code. And if you make the text box large enough (and anchor to the right bottom), then you can re-size the window.

eg this:

enter image description here

I also used a fixed font size for the text box (Courier new 12).

So above is rather bare bones. If you actually really looking to expand on this? Then I think the other links and sample code are better examples.

I am tempted to post a shell() command with the "pipe" > redirection of output to a text file. but, then that would require you to read a created text file for each commands output from a text file.

  • Related