Guys just wondering how can I create a program that does specific actions just by pressing any of the alphanumeric keys on my keyboard instead of the very traditional clicking of a button in a GUI.

Example, I want to close the window just by pressing the letter x on my keyboard. Is that possible? how?

5 Years
Discussion Span
Last Post by Reverend Jim

The first step is to set the form property KeyPreview to True. Once you have done that you can add a form level handler to process keys. A sample one (from one of my projects) is

Private Sub frmMain_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

        'This handler provides functionality for application hotkeys    

        Select Case Asc(e.KeyChar)
            Case 1                                  'ctrl-A (add author)
                e.Handled = True
            Case 14                                 'ctrl-N (New)  
                e.Handled = True
            Case 16                                 'ctrl-P (print)
                e.Handled = True
            Case 19                                 'ctrl-S (save)      
                e.Handled = True
            Case 20                                 'ctrl-T (add title) 
                e.Handled = True
        End Select

    End Sub

For keys A-Z you can use Keys.A, Keys.B, etc. instead of their numeric values for better readability. My code uses control keys. You have to set e.Handled to True to prevent any other handlers from processing the key press event.

Edited by Reverend Jim: n/a


This is very helpful! Thank you reverend_Jim, I guess you should be revered!

I'll try this when I create my next program


I changed this thread back to Unresolved because I have another issue here. How about if I want to use the Navaigation Keys instead or the Numeric keys, or the Space Bar?


It's generally not a good idea to trap unmodified keys (as in un-alt or un-ctrl) because that prevents you from doing things like typing in text fields, etc unless you specifically test for that in the key events at the form level. If you want to use the arrow keys then test for e.KeyCode = Keys.UP (for example) in the form.KeyDown handler.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.