如何在键盘上检测[上,下,左,右]键。 [英] How to detect keys [up, down, left, right] on keyboard.
问题描述
如何检测键盘上的键[上,下,左,右]。
How to detect keys [up, down, left, right] on keyboard.
推荐答案
如果您使用的是Windows窗体,请在构造函数中添加:
If you are using Windows Forms, add this in the constructor:
Me.KeyPreview = True
然后创建此方法:
And then create this method:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.Up
' up arrow
Exit Select
Case Keys.Down
' down arrow
Exit Select
Case Keys.Left
' left arrow
Exit Select
Case Keys.Right
' right arrow
Exit Select
End Select
End Sub
设置 KeyPreview
到 True
确保 Form1_KeyDown
将永远如果按下某个键,即使焦点位于另一个控件上,也可以调用,例如 TextBox
。
如果您使用的是WPF:
Setting KeyPreview
to True
makes sure that the Form1_KeyDown
will always be called if a key is pressed, even if the focus is on another control, such as a TextBox
.
If you are using WPF:
Private Sub MainWindow_PreviewKeyDown(sender As Object, e As KeyEventArgs) Handles Me.PreviewKeyDown
Select Case e.Key
Case Key.Up
' up arrow
Exit Select
Case Key.Down
' down arrow
Exit Select
Case Key.Left
' left arrow
Exit Select
Case Key.Right
' right arrow
Exit Select
End Select
End Sub
在WPF中, PreviewKeyDown
事件与Windows窗体中的 KeyPreview
属性具有相同的目的。如果您不想这样,只需使用 KeyDown
。
如果您使用的是控制台应用程序:
In WPF, the PreviewKeyDown
event has the same purpose as the KeyPreview
property in Windows Forms. If you don't want that, just use KeyDown
.
If you are using a Console Application:
Dim c As ConsoleKeyInfo = Console.ReadKey()
Select Case c.Key
Case ConsoleKey.UpArrow
' up arrow
Exit Select
Case ConsoleKey.DownArrow
' down arrow
Exit Select
Case ConsoleKey.LeftArrow
' left arrow
Exit Select
Case ConsoleKey.RightArrow
' right arrow
Exit Select
End Select
请注意,这仅在您调用 Console.ReadKey()
时才有效。
有一个名为 Control.KeyDown [ ^ ]和 K eys [ ^ ] .NET中的枚举。
-KR
There's a event called Control.KeyDown[^] and Keys[^] enumeration in .NET.
-KR
这篇关于如何在键盘上检测[上,下,左,右]键。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!