Creating Shortcuts in Code


I apologize for my hiatus from blogging. Some things out of my control occurred. Everything is going smoothly again and to start things off I have decided to revive a very old (but still relevant) tip I published on on 01-SEP-1999. The tip shows how you can create shortcuts for actions/menus in code.


[intense_hr size=”medium” shadow=”2″ accent_width=”30″ accent_height=”3″]

Have you ever wondered how to create menu/action shortcuts in code and found the Delphi help system short in this area? If you have then read on…

The Delphi help system has an example on how to create a shortcut, unfortunately they fall short in fully describing this technique. Their example is as follows:

This code creates a shortcut, Ctrl+O, at run time and assigns it to the Open command on a File menu.
[intense_code type=”block”]
  OpenCommand.ShortCut := ShortCut(Word(‘O’), [ssCtrl]);

However their example only shows how to create a shortcut like Ctrl+O. What if you wanted something like Alt+BkSp of Ctrl+Enter. Well after some digging I found a function called TextToShortCut, however the Delphi help system suggests not using this function if you can create the shortcut using the ShortCut function. Their reasoning is that a call to ShortCut is more efficient than a call to TextToShortCut. Well if code speed is an issue for you then the following table lists the keys for the Key parameter to the ShortCut function.


Backspace 8
Tab 9
Enter 13
Escape 27
Space 32
Page Up 33
Page Down 34
End 35
Home 36
Left 37
Up 38
Right 39
Down 40
Insert 45
Delete 46
F1..F12 112..123
F13..F24 124..135
Semicolon ; 186
Equals = 187
Comma , 188
Minus  189
Period . 190
Forward Slash / 191
Tick ` 192
Left Bracket [ 219
Backslash \ 220
Right Bracket ] 221
Single Quote  222
Forward Slash / 226 I’m not sure why this character has two possible values.


With this table handy, we can create a call to shortcut like this:


[intense_code type="block"]actSomeAction.ShortCut := ShortCut(13, [ssCtrl]);[/intense_code]


and actSomeAction’s ShortCut would be set to Ctrl+Enter


You should still follow the Delphi help system’s example if you need to create a ShortCut like Ctrl+A.


That’s all there is to creating menu/action shortcuts in code.




Leave a comment