TPopupMenu is a component in Delphi that allows you to create a context menu (also known as a right-click menu) for your application. Here is an example of how to use TPopupMenu:
- First, you need to add the TPopupMenu component to the component palette of your Delphi IDE.
- Next, you can drop the TPopupMenu component onto your form.
- You can then add items to the menu by clicking on the component and using the Object Inspector to add items. You can set the caption of the item and the OnClick event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
procedure TForm1.PopupMenu1Popup(Sender: TObject); var Item: TMenuItem; begin Item := TMenuItem.Create(PopupMenu1); Item.Text := ‘Menu Item’; Item.OnClick := HandleMenuItemClick; PopupMenu1.Items.Add(Item); end; procedure TForm1.HandleMenuItemClick(Sender: TObject); begin ShowMessage(‘Menu Item clicked’); end; |
- You can also add sub-items to the menu items by creating new TMenuItem objects and adding them to the Items property of the parent item.
1234567891011121314151617181920procedure TForm1.PopupMenu1Popup(Sender: TObject);varItem, SubItem: TMenuItem;beginItem := TMenuItem.Create(PopupMenu1);Item.Text := ‘Menu Item’;Item.OnClick :=HandleMenuItemClick;PopupMenu1.Items.Add(Item);SubItem := TMenuItem.Create(PopupMenu1);SubItem.Text := ‘Sub-Menu Item’;SubItem.OnClick := HandleSubMenuItemClick;Item.AddObject(SubItem);end;procedure TForm1.HandleSubMenuItemClick(Sender: TObject);beginShowMessage(‘Sub-Menu Item clicked’);end;
5. To show the menu, you need to associate the TPopupMenu component with a control (such as a button or a form) by setting thePopupMenu
property of that control to the TPopupMenu component.
1Button1.PopupMenu := PopupMenu1;
6. To show the menu when the user right-clicks on the control, you can use the OnContextPopup event of the control.
1234procedure TForm1.Button1ContextPopup(Sender: TObject; MousePos: TPointF; var Handled: Boolean);beginPopupMenu1.Popup();end;
It’s important to note that, you can also use the Popup method of the TPopupMenu component to programmatically show the menu, also you can use the OnPopup event of the TPopupMenu component to perform an action when the menu is displayed.
Leave a Reply