Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect popup of a sub-menu of a popup menu (and how to populate it dynamically)?

Tags:

winapi

delphi

I have a popup menu which contains several menu items and one of them can have child items. This entry has a little arrow on the right and when you hover your mouse over it, a sub-menu will open (without clicking). Now I want to populate this sub-menu at runtime, but only if the user actually opens it. If the user never opens the sub-menu, it will be empty (maybe contain a placeholder). How could I accomplish this? Is it even possible to modify a popup-menu when it is already visible?

Thanks for your help!

like image 444
Heinrich Ulbricht Avatar asked Dec 28 '22 17:12

Heinrich Ulbricht


1 Answers

There is no difference between submenus in standard menus or context (popup) menus: If a menu item has a submenu attached, then its OnClick event will fire just before the submenu is shown (note that you don't need to click for it to show up), and in that event handler you can modify the submenu (either set properties of existing items, or add new items / delete existing items).

Some demo code about dynamically adding and removing items:

procedure TForm1.FormCreate(Sender: TObject);
var
  Popup: TPopupMenu;
  Item, SubItem: TMenuItem;
begin
  Popup := TPopupMenu.Create(Self);
  PopupMenu := Popup;
  Item := TMenuItem.Create(Popup);
  Item.Caption := 'Test submenu';
  Item.OnClick := PopupClick;
  Popup.Items.Add(Item);

  SubItem := TMenuItem.Create(Item);
  SubItem.Caption := 'dummy';
  Item.Add(SubItem);
end;

procedure TForm1.PopupClick(Sender: TObject);
var
  SubmenuItem, Item: TMenuItem;
begin
  SubmenuItem := Sender as TMenuItem;
  // delete old items (leave at least one to keep the submenu)
  while SubmenuItem.Count > 1 do
    SubmenuItem.Items[SubmenuItem.Count - 1].Free;
  // create new items
  while SubmenuItem.Count < 3 do begin
    Item := TMenuItem.Create(SubmenuItem);
    Item.Caption := Format('new item created %d', [GetTickCount]);
    SubmenuItem.Add(Item);
  end;
end;
like image 133
mghie Avatar answered Dec 31 '22 13:12

mghie