pwalaako2 pwalaako2 - 7 months ago 16
Vb.net Question

how to create button shortcuts in vbnet

I tried creating keyboard shortcuts for my buttons.

Here is my code

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


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.

additional info:


  • the functions
    addentry
    and
    editentry
    will just call the
    form_addedit

  • btn_add
    will call for
    addentry

  • btn_edit
    will call for
    editentry


Answer

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 is 17 and Keys.N is 78, so you're literally writing:

If 17 + 78 Then

Which will always return True because it's greater than 0.

To do what you ask you must check which key was pressed by checking the event arguments (EventArgs) passed to the event.

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