formsdelphikeystroketmemonon-modal

How can I prevent the main form capturing keystrokes in a TMemo on another non-modal form?


I have an app that opens a non-modal form from the main form. The non-modal form has a TMemo on it. The main form menu uses "space" as one of its accelerator characters.

When the non-modal form is open and the memo has focus, every time I try to enter a space into the memo on the non-modal form, the main form event for the "space" shortcut fires!

I have tried turning MainForm.KeyPreview := false while the other form is open but no dice.

Any ideas?


Solution

  • Disable the menu item on the main form while the memo has focus, and re-enable it when the memo loses it. You can do this from the TMemo.OnEnter and TMemo.OnExit events.

    procedure TOtherForm.Memo1Enter(Sender: TObject);
    begin
      if Application.MainForm is TYourMainForm then
        TYourMainForm(Application.MainForm).MenuItemWithSpace. Enabled := False;
    end;
    
    procedure TOtherForm.Memo1Exit(Sender: TObject);
    begin
      if Application.MainForm is TYourMainForm then
        TYourMainForm(Application.MainForm).MenuItemWithSpace. Enabled := True;
    end;
    

    The use of Application.MainForm and the typecast are to prevent hard-coding in a form variable name in the child form.