我正在制作一个使用热键的应用程序。在设置表单中,用户可以通过单击按钮(将外观设置为按钮的复选框)设置热键,然后将按钮文本设置为该键。
问题是我找不到向用户显示密钥名称的方法。当用户点击返回键(例如)时,它会显示“13”。如何在没有巨大的if / switch语句的情况下向用户显示密钥名称?
我目前的代码:
Private Sub SelectkeyBtn_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles SelectkeyBtn.KeyDown
If SelectkeyBtn.Checked = True Then
SelectkeyBtn.Text = e.KeyData
SelectkeyBtn.Checked = False
End If
End Sub
修改
我发现了vb.net get name of key from e.keydata这对我有所帮助。
我的代码现在看起来像这样:
<DllImport("User32.dll")> _
Public Shared Function ToAscii(ByVal uVirtKey As Integer, ByVal uScanCode As Integer, ByVal lpbKeyState As Byte(), ByVal lpChar As Byte(), ByVal uFlags As Integer) As Integer
End Function
<DllImport("User32.dll")> _
Public Shared Function GetKeyboardState(ByVal pbKeyState As Byte()) As Integer
End Function
Public Shared Function GetAsciiCharacter(ByVal uVirtKey As Integer) As Char
Dim lpKeyState As Byte() = New Byte(255) {}
GetKeyboardState(lpKeyState)
Dim lpChar As Byte() = New Byte(1) {}
If ToAscii(uVirtKey, 0, lpKeyState, lpChar, 0) = 1 Then
Return Convert.ToChar((lpChar(0)))
Else
Return New Char()
End If
End Function
Private Sub SelectkeyBtn_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles SelectkeyBtn.KeyDown
If SelectkeyBtn.Checked = True Then
SelectkeyBtn.Text = GetAsciiCharacter(e.KeyData)
SelectkeyBtn.Checked = False
End If
End Sub
当我按下键盘上的键,如a,z,f,e,1,+,/ ..时,这是有效的。
当我按DELETE,F2,NUMLOCK等按钮文本为空时..(见截图)
大卫,