I’m trying to do a thing where the user can select their own shortcut keys, and I want to prompt them with a “press your desired shortcut key now” window.
Then obviously in the main program loop I’ll need to check for those keys.
Targets are Windows and Mac.
Is there a better way to do this other than a gigantic Select Case block testing every combination of keys and modifiers?
Edit: I should add that I think I will already will need to do a big Select Case block in order to get a text description of every key so I can display the user’s choice back to them in the UI.
If the items you wish to trigger are menu items you can assign the ShortCut property of the appropriate menu item. The system will then trigger things for you.
If you are just using random keys you could create an array of them (in a set order) and then use IndexOf to see if they are in the set and which it is:
Simple example. The app can respond, by default to L, R, U and D by moving something left right up or down. So we have an array of those letters:
Var aKeys() as String = Array( "L", "R", "U", "D" )
To allow customisation, you can then provide a mechanism to change the letters for elements 0, 1, 2 or 3.
When the user presses a key you can test if it one of the set as follows:
Var theKey as Integer = aKeys.IndexOf( thisKey )
theKey now tells you which of your actions you need to perform. ie 0 for the action that initially was set o “L”, even if they change the letters.
You don’t need a case statement for the descriptions either.
Var aDescriptions() as string = Array( "Move Left", "Move Right", "Move Up", "Move Down" )
Does that make sense?
I think the easiest way to do this is in the KeyDown event of a TextField, but some keys don’t register (like Pause/Break). You can position the TextField off-screen if you just want to present a label or other UI design. You’ll want to convert to something readable for the user as you mentioned but, with three CheckBoxes and a TextField, I imagine this giving you the basic means of allowing the user to define key combinations:
Function KeyDown(key As String) Handles KeyDown as Boolean
me.Text = key.Asc.ToString( "#" )
shiftCheck.Value = Keyboard.AsyncShiftKey
controlCheck.Value = Keyboard.AsyncControlKey
altValue.Check = Keyboard.AsyncAltKey
There are a number of other methods, such as polling the Keyboard class using a timer, or via declares into system functions for the target OS. There are some other topics that cover these which you should find pretty quickly in a search for “hotkey”.