Jump to content
Dmitry Onoshko

Limit TAction shortcut to a particular control

Recommended Posts

Suppose we have a form to edit information about some items. The form has a dozen of TEdit’s and a TListView that represents file attachments for the item. Naturally, the TListView has a TPopupMenu assigned to it, and each TPopupMenu has a TAction assigned.

 

Now, I want to assign shortcuts to the popup menu items: «Num +» to add a new file attachment, «Del» to remove selected attachments, etc. Now, here’s the problem: I obviously want Num + and Del only work this way inside the TListView, since in TEdit’s these keys already have well-defined and frequently used meanings.

 

Handling TForm.OnShortCut doesn’t help: neither value for Handled parameter causes the VCL to think the key should be passed to the control. The obvious solution then is to just handle the keys on TListView.OnKeyDown and remove them from TAction’s, but that would cause the shortcuts to disappear from menu items. Which, in turn, could probably be solved by messing with TMenuItem.Caption and #9 character (?) but would also make it wrong if the shortcut changes some day. Changing shortcuts to something like «Ctrl+Num +» and «Ctrl+Del» makes the shortcuts too complex for the case when the TListView is already focused, so is also not the best option.

 

I wonder, what is the best possible solution for such case? Basically, what I need is a way to make TAction shortcut local to a control (make the TAction fire only when the control is focused).

Share this post


Link to post

I ran into this limitation of actions quite a few years ago, especially with commonly used shortcuts like Ctrl+C/V etc. I solved this with a descendant TAction class which overrides HandleShortCut and only calls inherited, if Screen.ActiveControl or any of it's owners is the corresponding WinControl and otherwise returns False.

 

If you happen to have more than one action with the same shortcut associated to different controls, you also need to override the .IsShortcut method of the form and reimplement it without stopping at the first action with that shortcut. Not ideal, but that's the only real solution for things like Ctrl+C/V if you consider that when e.g. editing a list view, you want those default shortcuts to work in the edit - something that wouldn't work if you enable the action when the control is focused.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×