Delphi/Lazarus: Assign Shortcut for MenuItem in Code
Question by Compi | 2018-02-01 at 15:28
I want to set the shortcut for a menu item within my code instead of from the Object Inspector by hand. In the Object Inspector you have a drop-down list where you can select your desired shortcut.
However, when writing the following line in code:
MenuItem.ShortCut := 'F1';
I get the following error message:
Error: Incompatible type for arg no. 1: Got "Constant String", expected "TShortCut"
What am I doing wrong here? In the Object Inspector, you also select a string, but in code, the compiler complains that I have passed a string. Or is it possible to change this property only via the inspector?
Related Topics
Windows: How to run a Program as Administrator - Once, Always or with Shortcut
Tutorial | 0 Comments
Delphi: Global Treatment of Errors (Exceptions)
Tutorial | 0 Comments
Delphi/Lazarus: How to set up a Link to a Website in an Application
Tutorial | 0 Comments
Delphi/Lazarus: Select all with CTRL+A in ListView
Tip | 0 Comments
Delphi/Lazarus: 3 Ways to round a Number to X Decimal Places
Tutorial | 7 Comments
Delphi/Lazarus: Delete selected Items from ListBox using DEL-Key
Tip | 3 Comments
Delphi: Multiline Caption for TLabel (at Run Time and Design Time)
Tutorial | 1 Comment
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
A change or assignment of a shortcut is also possible in code. However, we can not just pass a string here because TShortCut is of type Word.
Fortunately, Delphi and Lazarus provide the TextToShortCut() function, which allows us to easily convert a string to the required numeric value.
So in your example, you can write:
The function TextToShortCut() transforms the string representation of a keyboard shortcut into the code representation of the same keyboard shortcut. For the opposite way there is the function ShortCutToText() available. Incidentally, this function is also called internally in the IDE when setting the shortcut, so that you can easily enter a shortcut as a string from the Object Inspector.
Another useful function is ShortCutToKey(). This function can be used to split the string representation of a key combination into both the key and the ShiftState.
2018-02-01 at 20:15