Search code examples
delphievent-handlingcontrolsmouseeventvcl

Is possible for a menu item to receive an OnClick event even when it's not enabled?


I'm trying to enable an Administrator to enable/disable menu items in the main menu of my Application by Ctrl+Clicking them. To do that I've injected the TMenuItem class in my main form with a custom version and overridden the Click virtual method, like so:

uses
  Forms, Menus;

type
  TMenuItem = class(Menus.TMenuItem)
  public
    ControlActivationState: Boolean;
    procedure Click; override;
  end;

  TMyMainForm = class(TForm)

...

procedure TMenuItem.Click;
begin
  if ControlActivationState and IsKeyPressed(VK_CONTROL) then
    Self.Enabled := not Self.Enabled
  else
    inherited;
end;

It works, but only for the top level menu. Why the top level menu items receives OnClick events even when they are disabled and the other menu items don't? Is there a way to make the child menu items receive those events too?


Solution

  • The top level OnClick event is triggered by receipt of a WM_INITMENUPOPUP message. That message is sent even when the top level item is disabled. I'm not sure why it is sent in that scenario, but it is. And the same is true for a sub-item that has children.

    However, for a sub-item without children, the OnClick is triggered by a WM_COMMAND message. But the system never even sends the message if the menu item is disabled.

    What you are attempting to do cannot be readily done. The only way I can see you doing it is to handle the raw mouse and keyboard events. Personally, I would not contemplate doing so.