Search code examples
delphiwinapimenuitemdelphi-11-alexandria

How to get the MenuItem name when right-clicking any menu item?


In a 32-bit Delphi 11 VCL Application on Windows 10, when RIGHT-CLICKING any menu item, I need to get the name of the clicked MenuItem.

I use a TApplicationEvents component and this code to get notified when I click on any menu item:

procedure TformMain.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
begin
  case Msg.message of
    Winapi.Messages.WM_COMMAND:
      begin
        CodeSite.Send('TformMain.ApplicationEvents1Message: WM_COMMAND');
      end;
  end;
end;

However:

  1. How to get notified only when RIGHT-clicking the menu item?

  2. How to get the NAME of the clicked MenuItem?


Solution

  • Since I have several forms in my application and several (popup) menus on each of these forms, a special solution is needed here:

    procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
    begin
      case Msg.message of
          Winapi.Messages.WM_COMMAND:
          begin
            // Todo: Check HERE for RightMouseButtonDown - BUT HOW? (Or how to check HERE for modifier keys?)
    
            var ThisMenuItem := GetMenuItem(Msg.wParam);
            if Assigned(ThisMenuItem) then
            begin
              CodeSite.Send('TForm1.ApplicationEvents1Message: Clicked MenuItem Name', ThisMenuItem.Name);
            end;
    
          end;
      end;
    end;
    
    function TForm1.GetMenuItem(const aWParam: NativeUInt): TMenuItem;
    var
      ThisMenuItem: TMenuItem;
    begin
      Result := nil;
      var ThisForm := Screen.ActiveForm; // works on any form in the application
      for var i := 0 to ThisForm.ComponentCount - 1 do
      begin
        if ThisForm.Components[i] is TMenu then
        begin
          ThisMenuItem := TMenu(ThisForm.Components[i]).FindItem(aWParam, fkCommand);
          if Assigned(ThisMenuItem) then
          begin
            Result := ThisMenuItem;
            EXIT;
          end;
        end;
      end;
    end;