【问题标题】:Trying to make command like "Shell" with commands with RichTextBox尝试使用 RichTextBox 的命令制作类似“Shell”的命令
【发布时间】:2015-06-03 00:12:34
【问题描述】:

尝试使用带有 RichTextBox 的命令来创建类似 Shell 的命令。

任何人都可以制作一个简单的方法吗? 我在整个网络上搜索这个找不到办法。 所以它应该像任何终端/外壳/控制台应用程序一样 所以我可以简单地添加自定义命令,比如 whatismyip 它会显示我的 IP 地址等。

应该像this。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
  For I As Integer = 0 To RichTextBox1.Lines.Count - 1 
    Dim Parts() As String = RichTextBox1.Lines(I).Split 
    Select Case Parts(0).ToUpper 
      Case "getip" 
        RichTextBox1.AppendText("SYS $~ 127.0.0.1") 
      Case Else 
        RichTextBox1.AppendText("SYS $~ Invalid command.") 
    End Select 
  Next 
End Sub

【问题讨论】:

  • 如果这就是您拥有的所有条件,那应该是简单的If/Else 而不是Select Case

标签: vb.net shell terminal


【解决方案1】:

试试这个:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    commands = New Dictionary(Of String, Func(Of String, IEnumerable(Of String), String))() From _
    { _
        {"getip", Function(c, ps) Me.GetIP().ToString()}, _
        {"nop", Function(c, ps) "No Command"} _
    }
End Sub

Private commands As Dictionary(Of String, Func(Of String, IEnumerable(Of String), String)) = Nothing

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim command = {"nop"}.Concat(Me.RichTextBox1.Lines) _
                  .Reverse().First(Function(l) Not [String].IsNullOrWhiteSpace(l))

    If (If(Me.RichTextBox1.Lines.LastOrDefault(), "")).Length > 0 Then
        Me.RichTextBox1.AppendText(Environment.NewLine)
    End If

    Dim parts = command.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
    Dim result = "Invalid Command"
    If commands.ContainsKey(parts(0).ToLower()) Then
        result = commands(parts(0))(parts(0), parts.Skip(1).ToArray())
    End If
    Me.RichTextBox1.AppendText("SYS $~ " + result)
End Sub

Private Function GetIP() As String
    Dim host As IPHostEntry
    Dim localIP As String = "?"
    host = Dns.GetHostEntry(Dns.GetHostName())
    For Each ip As IPAddress In host.AddressList
        If ip.AddressFamily = AddressFamily.InterNetwork Then
            localIP = ip.ToString()
        End If
    Next
    Return localIP
End Function

您需要添加以下导入:

Imports System.Net
Imports System.Net.Sockets

然后您可以为每个命令构建字典。

【讨论】:

  • 感谢您的@Enigmativity。可以提供前缀吗?我的意思是像 dim user 所以它将命令拆分为: Userpc $~ getip 和参数呢?
  • @Shahar - 我不知道你说的前缀是什么意思。是"SYS $~ "吗?此代码当前处理参数 - 那是 Func(Of String, IEnumerable(Of String), String) 签名。 Func 采用 String(命令)和 IEnumerable(Of String)(' ' 与命令分隔的参数列表)。
猜你喜欢
  • 2016-10-10
  • 2021-01-25
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 2020-12-05
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多