Check that Hotkey is valid with RegExMatch

Helpful script writing tricks and HowTo's
Snacksy
Posts: 2
Joined: 15 Dec 2022, 17:01

Check that Hotkey is valid with RegExMatch

Post by Snacksy » 15 Dec 2022, 17:14

The current implementation of gLabel for GUI Hotkey element fires even when the hotkey is invalid.

For example if you want to add CTRL + E the label will run once for CTRL and then for CTRL+E (written as ^e in ahk)

Using RegExMatch we can check that the hotkey is valid before implementing it.

Code: Select all

Gui, Add, Hotkey, vValue gHotkeyLabel
Gui, Show,,
return

HotKeyLabel:
; check that hotkey is valid
if (RegExMatch(Value, "[^#+!^]")) return
MsgBox Recieved valid hotkey %Value%

lexikos
Posts: 9688
Joined: 30 Sep 2013, 04:07
Contact:

Re: Check that Hotkey is valid with RegExMatch

Post by lexikos » 16 Dec 2022, 01:38

This is misleading:

Code: Select all

if (RegExMatch(Value, "[^#+!^]")) return
The return has no effect. It is interpreted as a variable, and is concatenated with the result of RegExMatch. The variable is empty, so it doesn't affect the result.

This is misleading:

Code: Select all

; check that hotkey is valid
if (RegExMatch(Value, "[^#+!^]"))
There are many invalid strings that this would consider to be valid hotkeys. It is safe to use only in the context of the Hotkey control, which always returns either a valid string of modifiers without a key (e.g. ^ corresponding to the text "Ctrl +"), or a valid hotkey.

It may be better to say "check that the hotkey is complete" or "check that the value has something other than modifier symbols".

There is a possibility that it may give the wrong result if #+!^ are assigned directly to keys in the keyboard layout; i.e. if the Hotkey control can ever return ++ to mean Shift+plus. This does not happen with the US layout, because these characters are produced by holding Shift and pressing some other key.

Post Reply

Return to “Tutorials (v1)”