如何在 vbnet 中创建按钮快捷方式 [英] how to create button shortcuts in vbnet
问题描述
我尝试为我的按钮创建键盘快捷键.
I tried creating keyboard shortcuts for my buttons.
这是我的代码
Private Sub form_main_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If Keys.ControlKey + Keys.N Then
'btn_add.PerformClick()
addentry()
ElseIf Keys.ControlKey + Keys.E Then
'btn_edit.PerformClick()
editentry()
End If
End Sub
问题是即使我按下其他按钮,该功能仍然被调用.我也尝试使用表单 keydown
属性,但结果仍然相同.
The problem is even when I press other buttons the function is still called. I also tried using form keydown
property but the result is still the same.
附加信息:
addentry
和editentry
函数只会调用form_addit
btn_add
将调用addentry
btn_edit
将调用editentry
- the functions
addentry
andeditentry
will just call theform_addedit
btn_add
will call foraddentry
btn_edit
will call foreditentry
推荐答案
首先 Keys.***
只是一个枚举.其中的每个条目只是一个代表密钥代码的数字.因此,您目前只是将数字相加.
First of all Keys.***
is just an enumeration. Every entry in it is just a number representing a key code. So you are currently just adding numbers together.
Keys.ControlKey
是 17 而 Keys.N
是 78,所以你实际上是在写:
Keys.ControlKey
is 17 and Keys.N
is 78, so you're literally writing:
If 17 + 78 Then
哪个总是返回 True
因为它大于 0.
Which will always return True
because it's greater than 0.
要执行您的要求,您必须通过检查传递给事件的事件参数 (EventArgs) 来检查按下了哪个键.
To do what you ask you must check which key was pressed by checking the event arguments (EventArgs) passed to the event.
但是由于您使用的是 KeyPress
事件,因此您无法从事件参数中获取键枚举,因此我建议您改用 KeyDown
事件.>
But since you are using the KeyPress
event you cannot get the key enumeration out of the event args, so I recommend you to use the KeyDown
event instead.
Private Sub form_main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.Control = True AndAlso e.KeyCode = Keys.N Then
addentry()
ElseIf e.Control = True AndAlso e.KeyCode = Keys.E Then
editentry()
End If
End Sub
这篇关于如何在 vbnet 中创建按钮快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!