Delphi – TMenuItem-Shortcuts overwrite Shortcuts from Controls (TMemo)

delphidelphi-2009

What can I do that shortcuts for menu items don't overwrite those from local controls?
Imagine this simple app in the screenshot. It has one "undo" menu item with the shortcut CTRL+Z (Strg+Z in German) assigned to it. When I edit some text in the memo and press CTRL+Z I assume that the last input in the memo is reverted, but instead the menu item is executed.

This is especially bad in this fictional application because the undo function will now delete my last added "Item 3" which properties I was editing.

CTRL+Z is just an example. Other popular shortcuts cause similar problems (Copy&Paste: CTRL+X/C/V, Select all: CTRL+A).

Mini Demo with menu item with CTRL+Z short-cut http://img31.imageshack.us/img31/9074/ctrlzproblem.png

Best Answer

The VCL is designed to give menu item shortcuts precedence. You can, however, write your item click handler (or action execute handler) to do some special handling when ActiveControl is TCustomEdit (call Undo, etc.)

Edit: I understand you don't like handling all possible special cases in many places in your code (all menu item or action handlers). I'm afraid I can't give you a completely satisfactory answer but perhaps this will help you find a bit more generic solution. Try the following OnShortCut event handler on your form:

procedure TMyForm.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
var
  Message: TMessage absolute Msg;
  Shift: TShiftState;
begin
  Handled := False;
  if ActiveControl is TCustomEdit then
  begin
    Shift := KeyDataToShiftState(Msg.KeyData);
    // add more cases if needed
    Handled := (Shift = [ssCtrl]) and (Msg.CharCode in [Ord('C'), Ord('X'), Ord('V'), Ord('Z')]);
    if Handled then
      TCustomEdit(ActiveControl).DefaultHandler(Message);
  end
  else if ActiveControl is ... then ... // add more cases as needed
end;

You could also override IsShortCut method in a similar way and derive your project's forms from this new TCustomForm descendant.

Related Topic