Home > other >  Unload Form1 when embedded cmd process ends
Unload Form1 when embedded cmd process ends

Time:07-28

I have found some code which runs a cmd.exe shell interactively in a TextBox; later on I will replace cmd.exe with a different character based application.

Here's the code:

Public Class Form1
Dim P As New Process
Dim SW As System.IO.StreamWriter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.Text = "My title"
    AddHandler P.OutputDataReceived, AddressOf DisplayOutput
    P.StartInfo.CreateNoWindow() = True
    P.StartInfo.UseShellExecute = False
    P.StartInfo.RedirectStandardInput = True
    P.StartInfo.RedirectStandardOutput = True
    P.StartInfo.FileName = "cmd"
    P.Start()
    P.SynchronizingObject = TextBox1
    P.BeginOutputReadLine()
    SW = P.StandardInput
    SW.WriteLine()
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
End Class

When you enter the exit command, the cmd.exe process terminates.

I like my application to unload Form1 when this occurs, but I don't know how to implement this.

CodePudding user response:

Add this above End Sub in your Form1_Load Sub:

p.WaitForExit()
Form1.Close()
  • Since it looks like you're calling it from Form1 itself, you could also use Me.Close.
  • If Form1 is the only form and you want the whole application to close, you can use Application.Exit() instead.

Some references:

http://www.vb-helper.com/howto_net_start_notepad_wait.html

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.close?view=windowsdesktop-6.0

CodePudding user response:

As suggested by Jimi, I added the following line to he Form1_Load sub:

P.EnableRaisingEvents = True

and added:

Private Sub myProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles P.Exited
    Me.Close()
End Sub

This is working, thank you very much Jimi!

Kind regards,

Eric

  • Related