我正在VB.NEt中开发应用程序(Visual Studio 2017)我想向CMD发送一些命令并在多行文本框中接收输出。我该怎么办?并且只有一个cmd窗口应该可见
答案 0 :(得分:1)
有点谷歌搜索...
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
End Sub
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.CreateNoWindow = True '<---- if you want to not create a window
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
SW.WriteLine("exit") 'exits command prompt window
txtResults.Text = SR.ReadToEnd 'returns results of the command window
SW.Close()
SR.Close()
End Sub
答案 1 :(得分:1)
先前的答案几乎是正确的,但会引发跨线程错误。将cmd输出中的返回文本放入变量中,然后在按钮中的Sub后面单击,调用字符串,如下所示...
在表单上创建一个名为btnPowerShSend的按钮, 创建两个带有多行属性的文本框,其名称为: txtResults& txtScript
Public Class Form1
Dim retText As String
Private Sub BtnPowerShSend_Click(sender As Object, e As EventArgs) Handles btnPowerShSend.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
txtResults.Text = retText 'returns results of the command window
End Sub
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.CreateNoWindow = True '<---- if you want to not create a window
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
SW.WriteLine(txtScript.Text) 'the command you wish to run.....
SW.WriteLine("exit") 'exits command prompt window
retText = SR.ReadToEnd.ToString
SW.Close()
SR.Close()
End Sub
End Class