我发现一些代码可以在TextBox
中交互运行cmd.exe shell;稍后,我将用不同的基于字符的应用程序替换cmd.exe。
这是代码:
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
当您输入exit命令时,cmd.exe进程将终止。
我喜欢我的应用程序在出现这种情况时卸载Form1
,但我不知道如何实现。
根据吉米的建议,我在Form1_Load
子中添加了以下行:
P.EnableRaisingEvents = True
并添加:
Private Sub myProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles P.Exited
Me.Close()
End Sub
这是有效的;非常感谢吉米!
将其添加到Form1_Load
Sub:中的End Sub
之上
p.WaitForExit()
Form1.Close()
- 因为看起来是从
Form1
本身调用它,所以也可以使用Me.Close
- 如果
Form1
是唯一的表单,并且您希望关闭整个应用程序,则可以使用Application.Exit()
一些参考文献:
http://www.vb-helper.com/howto_net_start_notepad_wait.html
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.close?view=windowsdesktop-6.0