TMenuItems (C++)

From RAD Studio Code Examples
Jump to: navigation, search

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". Also, 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

void __fastcall TForm1::AddButtonClick(TObject *Sender)
{
	// The owner (PopupMenu1) will clean up this menu item.
	TMenuItem *NewItem = new TMenuItem(PopupMenu1); // Create the new item.
	int index = PopupMenu1->Items->Count;
	PopupMenu1->Items->Add(NewItem);// Add it to the Popupmenu.
	NewItem->Caption = "Menu Item " + IntToStr(index);
	NewItem->Tag = index;
	NewItem->OnClick = PopupMenuItemsClick;// Assign it an event handler.
	TNotifyEvent();
}

void __fastcall TForm1::PopupMenuItemsClick(TObject *Sender)
{
    TMenuItem *ClickedItem = dynamic_cast<TMenuItem *>(Sender);
    if (ClickedItem)
    {
        switch (ClickedItem->Tag)
		{
			case 0:
			{
				ShowMessage("first item clicked");
				break;
			}
			case 1:
			{
				ShowMessage("second item clicked");
				break;
			}
			case 2:
			{
				ShowMessage("third item clicked");
				break;
			}
			case 3:
			{
				ShowMessage("fourth item clicked");
				break;
			}
		}
    }
}

/*
To edit or destroy an item, grab its pointer 
using the Items property.
*/
void __fastcall TForm1::EditButtonClick(TObject *Sender)
{
    const int index = 1;
	TMenuItem *ItemToEdit = PopupMenu->Items->Items[index];
    ItemToEdit->Caption = "Changed Caption";
}

void __fastcall TForm1::DestroyButtonClick(TObject *Sender)
{
    const int index = 2;
	TMenuItem *ItemToDelete = PopupMenu->Items->Items[index];
    delete ItemToDelete;
}

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
	const int num_items = 4;
	for (int index = 0; index < num_items; ++index)
	{
		// The owner (PopupMenu1) will clean up this menu item.
		TMenuItem *NewItem = new TMenuItem(PopupMenu1); // Create the new item.
		PopupMenu1->Items->Add(NewItem);// Add it to the Popupmenu.
		NewItem->Caption = "Menu Item " + IntToStr(index);
		NewItem->Tag = index;
		NewItem->OnClick = PopupMenuItemsClick;// Assign it an event handler.
		TNotifyEvent();
	}
}

Uses