TMenuItems (Delphi)
From RAD Studio XE2 Code Examples
Language:
Description
This example demonstrates how to add and delete menu items to a pop-up menu at run time and assign an event handler to the OnClick event. Place a TPopupMenu and three buttons on the form named "AddButton", "EditButton", and "DestroyButton" and add OnClick events to all three buttons. Put the TPopupMenu in the PopupMenu property of the form. Place the PopupMenuItemsClick procedure in the TForm1 type declaration so that it can be used as the method call for the menu item OnClick event.
Code
type TForm1 = class(TForm) AddButton: TButton; EditButton: TButton; DestroyButton: TButton; PopupMenu1: TPopupMenu; procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DestroyButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public procedure PopupMenuItemsClick(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AddButtonClick(Sender: TObject); var index: Integer; NewItem: TMenuItem; begin // The owner (PopupMenu1) will clean up this menu item. NewItem := TMenuItem.Create(PopupMenu1); // Create the new item. index := PopupMenu1.Items.Count; PopupMenu1.Items.Add(NewItem);// Add it to the pop-up menu. NewItem.Caption := 'Menu Item ' + IntToStr(index); NewItem.Tag := index; NewItem.OnClick := PopupMenuItemsClick; // Assign it an event handler. end; procedure TForm1.PopupMenuItemsClick(Sender: TObject); begin with Sender as TMenuItem do begin case Tag of 0: ShowMessage('first item clicked'); 1: ShowMessage('second item clicked'); 2: ShowMessage('third item clicked'); 3: ShowMessage('fourth item clicked'); end; end; end; { To edit or destroy an item, grab its pointer using the Items property. procedure TForm1.EditButtonClick(Sender: TObject); var ItemToEdit: TMenuItem; begin ItemToEdit := PopupMenu.Items[1]; ItemToEdit.Caption := 'Changed Caption'; end; procedure TForm1.DestroyButtonClick(Sender: TObject); var ItemToDelete: TMenuItem; begin ItemToDelete := PopupMenu.Items[2]; ItemToDelete.Free; end; procedure TForm1.FormCreate(Sender: TObject); var index: Integer; NewItem: TMenuItem; begin for index := 0 to 3 do begin // The owner (PopupMenu1) will clean up this menu item. NewItem := TMenuItem.Create(PopupMenu1); // Create the new item. PopupMenu1.Items.Add(NewItem);// Add it to the pop-up menu. NewItem.Caption := 'Menu Item ' + IntToStr(index); NewItem.Tag := index; NewItem.OnClick := PopupMenuItemsClick; // Assign it an event handler. end; end;
Uses
- Vcl.Menus.TMenu.Items ( fr | de | ja )
- Vcl.Menus.TMenuItem.Add ( fr | de | ja )
- Vcl.Menus.TMenuItem.Caption ( fr | de | ja )
- System.Classes.TComponent.Tag ( fr | de | ja )
- Vcl.Menus.TMenuItem.OnClick ( fr | de | ja )
- Vcl.Controls.TControl.PopupMenu ( fr | de | ja )
- Vcl.Menus.TMenuItem.Count ( fr | de | ja )
- System.TObject.Free ( fr | de | ja )