Search code examples
vb.netkeyboard-shortcutskeypressshortcut

Specific keyboard characters to call specific button actions


When I start my program, and push the specified keys to call my button commands, it does not do anything.

The focus remains on one of the buttons and nothing occurs.

I've tried multiple codes from using KeyDown to KeyPress to codes that include vbKey.

I am very new to vb, so it is very likely that I just do understand what I am doing. :(

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.KeyPreview = True
End Sub

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.KeyCode = "/" Then
        Call Button1_Click(sender, e)
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    'Close Program

    Me.Close()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPMN.Click
    'Add +1 to PMN Textbox (txtPMN)

    txtPMN.Text = (Val(txtPMN.Text) + 1).ToString()

End Sub
End Class

I would like to simulate the clicking of certain buttons (activate the button code) when I press specific keys on the keyboard. For example: If I press "/" I would like Button1_Click to activate as if I clicked the button with the mouse. Then, if I push my next key ".", I would like Button2_Click to activate.

I do not want to use modifiers like: SHIFT, CTRL, ALT


Solution

  • Please try with keychar like this:

    Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If e.KeyChar = "/" Then
            Call Button1_Click(sender, New EventArgs)
        End If
    end sub
    

    when use keydown, the keycode for "/" key is OEM, depend the keyboard type, so char(e.keycode) may be not "/"