在vb.net中创建我自己的CMD

时间:2016-10-29 18:57:25

标签: vb.net shell cmd

我需要帮助解决这个我想要创建的程序。 我对编程很新,所以请耐心等待。

所以我现在想要创建的是我自己的命令提示符,然后说,让我在命令提示符下告诉你我想要的内容。

正如我们从Windows操作系统上的常规CMD所知,我们有输入框(或其他)我们可以用来输入命令,例如"启动google.com"或&#34 ; IPCONFIG"等等... 我们有输出,告诉我们输入命令的结果。

我想创建完全相同的东西,只需使用我自己的UI和一些我将要添加的附加内容。

这是我的问题,每当我在文本框中键入shell命令并执行它时,它会打印出异常消息,所以基本上它不会运行命令。

以下是代码:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
    If tmp.KeyChar = ChrW(Keys.Enter) Then
        Try
            Shell(TextBox1.Text)
            RichTextBox1.SelectionColor = Color.Green
            RichTextBox1.SelectedText = TextBox1.Text
        Catch ex As Exception
            RichTextBox1.Clear()
            RichTextBox1.SelectionColor = Color.Red
            RichTextBox1.SelectedText = ex.Message
        End Try
        TextBox1.Text = ""
    Else

    End If
End Sub

如果可能的话,我真的很喜欢一些例子,因为我是新手,如果没有例子我可能不会理解。

1 个答案:

答案 0 :(得分:1)

使用进程对象而不是shell是一个与cmd进行对话的选项。这是一个简单函数的示例,您可以将命令传递给它将返回命令的响应。此示例只执行一个命令/响应,但您可以使用下面显示的相同过程进入cmd.exe对话框:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    MsgBox(ExecuteCommand("ipconfig /all"))
End Sub

Private Function ExecuteCommand(ByVal command As String) As String
    Dim response As String = Nothing
    Dim p As New System.Diagnostics.Process
    Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
    With psi
        .UseShellExecute = False
        .RedirectStandardInput = True
        .RedirectStandardOutput = True
        .RedirectStandardError = True
        .CreateNoWindow = True
    End With
    p = Process.Start(psi)
    With p
        .StandardInput.WriteLine(command)
        .StandardInput.Close()
        If .StandardError.Peek > 0 Then
            response = .StandardError.ReadToEnd
            .StandardError.Close()
        Else
            response = .StandardOutput.ReadToEnd
            .StandardOutput.Close()
        End If
        .Close()
    End With
    Return response
End Function

正如您将看到的,如果您运行上面的代码,您当然可以使用像ipconfig这样的命令