Triggering default menu items from code #53

It's sometimes useful to be able to trigger the default menu item of a popup menu from code. Here is a routine that does just that for any popup menu.

uses
  Menus;

function TriggerDefaultMenuAction(const Menu: TMenu): Boolean;
  overload;
var
  Idx: Integer;
  MI: TMenuItem;
begin
  Assert(Assigned(Menu));
  Result := False;
  for Idx := 0 to Pred(Menu.Items.Count) do
  begin
    MI := Menu.Items[Idx];
    if MI.Default then
    begin
      MI.Click;
      Result := True;
      Break;
    end;
  end;
end;

The routine returns True if it found a default menu item and False if not.

TriggerDefaultMenuItem will also work with a main menu component, but it's not very useful since it will only examine the top level menu items, and it's very rare one of those is the default item.

You can adapt the code to trigger the default menu item of a sub menu as follows:

function TriggerDefaultMenuAction(const MenuItem: TMenuItem): Boolean;
  overload;
var
  Idx: Integer;
  MI: TMenuItem;
begin
  Assert(Assigned(MenuItem));
  Result := False;
  for Idx := 0 to Pred(MenuItem.Count) do
  begin
    MI := MenuItem.Items[Idx];
    if MI.Default then
    begin
      MI.Click;
      Result := True;
      Break;
    end;
  end;
end;

This code loops through the sub menu items of a menu item. If, for example, you had a File menu on a main menu (called File1) and that menu had a default entry, you could trigger it by calling:

TriggerDefaultMenuItem(File1);
Author: Peter Johnson
Contributor: Peter Johnson
Added: 2007/10/12
Last updated: 2007/10/12