命令问题VB

时间:2015-11-26 20:13:09

标签: vb.net cmd

所以,我在VB.net中制作一个控制台。我决定以Lua类型的方式使用子串方式。但是,在执行此操作时,如果我键入的内容不是命令,则会因错误而崩溃:“附加信息:索引和长度必须引用字符串中的位置。”

Public Class Form1
    Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
        Dim cmd As String = TextBox2.Text
        Dim l As Integer = Len(TextBox2.Text)
        Dim param As String
        If e.KeyCode = Keys.Enter Then
            '0 Param command
            If cmd = "script" Then
                Script.Show()
                TextBox2.Text = ""

                'Trying to avoide error "Additional information: Index and length must refer to a location within the string." 
            ElseIf Not cmd.Substring(0, 5) = "echo;" Or Not cmd.Substring(0, 9) = "download;" Then
                Return

                '1 Param cmd
            ElseIf cmd.Substring(0, 5) = "echo;" Then
                param = cmd.Substring(5)
                Me.TextBox1.Text = Me.TextBox1.Text + Environment.NewLine + param
                TextBox2.Text = ""

                '2 Param cmd
            ElseIf cmd.Substring(0, 9) = "download;" Then
                param = cmd.Substring(9)
                Me.TextBox1.Text = Me.TextBox1.Text + Environment.NewLine + param.Substring(0, param.IndexOf(";"c)) + param.Substring(param.IndexOf(";"c) + 1)
                TextBox2.Text = ""

            End If
        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

您无法尝试从不在字符串内的位置获取子字符串 但是,您可以使用更简单的方法来避免对输入文本的第一次检查,而不是尝试获取子字符串

    If cmd = "script" Then
       .....
    ElseIf cmd.StartsWith("echo;") Then
         .....
    ElseIf cmd.StartsWith("download;") Then
         ....
    Else
         Return
    End If