00 Votes

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?

3Best Answer3 Votes

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:

MenuItem.ShortCut := TextToShortCut('F1');

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

ReplyPositive Negative

Related Topics

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.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.