Tom Strong
Tom Strong

Reputation: 73

How to check the key pressed in VB

I am trying to make a program which needs you to select a hotkey, but you can only give a character from the code I've produced, where as I want to be able to set something like F9 as well. I have been through a few on this site and this is the closest to what I want. I'm using Visual Studio 2013.

This is what I've got so far.

Private Sub Configure_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyBase.KeyPress
    MsgBox("Your new hotkey is: " & e.KeyChar)
End Sub

Thanks in advance.

Upvotes: 2

Views: 532

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

The KeyPress event is not raised by non-character keys other than space and backspace; however, the non-character keys do raise the KeyDown and KeyUp events.

Set ReadOnly property of your TextBox1 to true and handle keyDown event:

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
    Me.TextBox1.Text = e.KeyData.ToString()
End Sub 

This shows also the key combinations in te text box, for example if you press Ctrl + Shift + F9 you will see F9, Shift, Control in text box.

You can use KeyCode, Modifiers and other properties of KeyEventArgs to gain information about keys.

Upvotes: 2

Related Questions