Making a program react to user keyboard keystrokes

Elvarg

New member
Joined
Nov 29, 2005
Messages
4
Programming Experience
Beginner
What is the simplest way to make a VB.NET program (very simple, single-module, doesn't use OO features other than default generated by Windows Forms) react to user keyboard keystrokes?

Simply put, I have a bunch of buttons, called, say, btnOne, btnTwo, btnThree etc. When clicked, they set someParameter = "one" (or "two" or "three"), and then call for someFunction() to execute (passing that parameter to it).

I need to make the program react to user keystrokes, so when the user hits 1 on their keyboard, btnOne is called, when 2, btnTwo, etc. I'd also be satisfied with creating new subs specifically to catch each type of keystroke, which themselves set the right parameter and call someFunction(). Whatever solution is simplest.

The program should react to user keystrokes at all times (regardless of what keystrokes has it caught before, and particularly regardless of what control currently has focus).

Also, I will be using buttons like btnSpace and btnEnter, and I need them to properly catch the keystroke SPACE or ENTER and invoke the right procedures, OVERRIDING their default action of "clicking" the currently selected control.

For example, the user just clicked btnThree with the mouse, and that button got focus. If the user presses ENTER or SPACE, the focused control btnThree would be clicked again. I don't want that. I need instead to have it trigger btnEnter / btnSpace.

Although if you can suggest how to automatically deselect controls after clicking, that would solve the last part of the problem. Other than the SPACE/ENTER problem, I don't have any fields where the user is to type text or otherwise use keyboard, so I don't need to worry about compatibility with textboxes etc. I also do not expect the user to navigate or operate controls using tab/arroweys.

Please offer simple solutions; I'm not very strong in VB.NET yet, and I'd really rather not have to work with includes, multiple modules, etc. I tried reading VB.NET help on KeyPress or KeyDown, but never managed to get anything working. For the same reason, I'd appreciate you giving explicit code as an example and not just some abstract advice.

Thanks.
 
What you normally do with controls to have them react to keyboard shortcuts is to use mnemonics. If you set the Text of a Button to "Button &1" then at run time that will be shown as "Button 1" and the user can "click" the button by pressing Alt+1. If you are determined that just the "1" key be needed then the easiest way is to set the KeyPreview of the form to True and handle the KeyPress event and catch whichever keys you are interested in. You can then call PerformClick on the Button.
 
Back
Top