Beranda > Delphi > Triggering default menu items from code

Triggering default menu items from code

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);
Iklan
Kategori:Delphi
  1. Desember 4, 2013 pukul 5:47 am

    After checing out a number off the articles on your web
    page, I truly like your techniqie of writing a
    blog. I boiokmarked it too my bookmark website list andd will be checking back in tthe nnear future.
    Please chehk outt my web site as well and tell me how you feel.

  2. Juni 16, 2014 pukul 10:07 am

    Hi, I do think this is a great blog. I stumbledupon it 😉 I am going to return yet again since I
    saved as a favorite it. Money and freedom is the best way to change, may you be rich and continue to help others.

  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: