如何在vb控制台模式下检测按键? [英] How can you detect key presses in vb console mode?
问题描述
我想开始制作一个包含菜单的程序,但我不想使用典型的选择情况,而是想以不同的方式来做.
I wanted to make a program involving a menu at the start but instead of using the typical select case I wanted to do it differently.
我希望它为用户提供一些选项,然后他们将使用箭头键在选项旁边移动一个小箭头.
I wanted it to give the user some options and then they would use the arrow keys to move a little arrow next to the options.
最后,按Enter键,然后进入所选的下一个屏幕.我一直在网上搜索,但只能在表单模式下找到此类内容,而不能在控制台上找到.如果无法做到这一点,请告诉我,我们将不胜感激.
Finally you press enter and then you would advance to the next screen that you selected. I have been searching the web but I could only find this kind of stuff in form mode, not console. If this isn't possible let me know and I would appreciate any feedback.
推荐答案
一种简单的方法是使用菜单类,该类将打印出菜单并突出显示传递给它的项目编号:
One simple way is with a menu class that will print out the menu and highlight the item number passed to it:
Class Menu
Private MenuList As New List(Of String)
Public ReadOnly Property LineCount As Integer
Get
Return MenuList.Count
End Get
End Property
Public Sub CreateNewMenu(strings As IEnumerable(Of String))
MenuList.Clear()
For Each s In strings
MenuList.Add(s)
Next
End Sub
Public Sub PrintMenu(highlight As Integer)
If highlight < 0 OrElse highlight > MenuList.Count - 1 Then
Throw New Exception("Invalid menu index")
End If
For I = 0 To MenuList.Count - 1
If I = highlight Then
SwapColors()
Console.WriteLine(MenuList(I))
Console.ResetColor()
Else
Console.WriteLine(MenuList(I))
End If
Next
End Sub
Private Sub SwapColors()
Dim temp = Console.BackgroundColor
Console.BackgroundColor = Console.ForegroundColor
Console.ForegroundColor = temp
End Sub
End Class
要使用它,如下所示:
Dim MainMenu As New Menu
MainMenu.CreateNewMenu(
{
"Option A",
"Option B",
"Option C"
})
Dim CurrentItem As Integer = 0
Dim CurrentKey As ConsoleKey
While CurrentKey <> ConsoleKey.Enter
Console.Clear()
MainMenu.PrintMenu(CurrentItem)
CurrentKey = Console.ReadKey(True).Key
If CurrentKey = ConsoleKey.UpArrow Then
CurrentItem -= 1
ElseIf CurrentKey = ConsoleKey.DownArrow Then
CurrentItem += 1
End If
CurrentItem = (CurrentItem + MainMenu.LineCount) Mod MainMenu.LineCount
End While
这将使用反转的颜色突出显示所选的项目,但是如果需要,可以很容易地更改为在将项目写入控制台时添加一个指示器.
This will use inverted colors to highlight the selected item, but this can easily be changed to add an indicator when writing the item to the console, if desired.
退出while循环时,CurrentItem
将保留所选菜单项的从0开始的索引.
When the while loop exits CurrentItem
will hold the 0-based index of the selected menu item.
这种方法的一个优点是,您可以拥有多个菜单集合,这些菜单集合将使您可以根据选择显示特定的菜单.
One advantage of this approach is that you can have several collections of menus that will allow you to show specific ones based on the selection.
这篇关于如何在vb控制台模式下检测按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!