Skip to main content

How to Create a Popup Menu at Runtime

  • 2 minutes to read

In this example, we demonstrate how to create a popup menu from scratch at runtime. This sample requires a form with a TMemo control placed on it. The popup menu is created when a user right-clicks the memo control. The popup menu includes five items: “Cut”, “Copy”, “Paste”, “Clear”, and “Select All”. The PopupMenuButtonClick procedure processes a user’s selection of a given menu item. The Memo1MouseDown procedure represents the TMemo.OnMouseDown event handler.

type
  TMainForm = class(TForm)
  private
    // ...
    procedure PopupMenuButtonClick(Sender: TObject);
    // ...
  end;
// ...
procedure TMainForm.PopupMenuButtonClick(Sender: TObject);
begin
  with Memo1 do
    case TdxBarButton(Sender).Tag of
      1: CutToClipboard;
      2: CopyToClipboard;
      3: PasteFromClipboard;
      4: ClearSelection;
      5: SelectAll;
    end;
end;
procedure TMainForm.Memo1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
const
  ButtonCount = 5;
  Captions: array[1..ButtonCount] of string = ('Cu&t', '&Copy', '&Paste', 'Cle&ar', '&Select All');
var
  PopupMenu: TdxBarPopupMenu;
  I: Integer;
  Buttons: array[1..ButtonCount] of TdxBarButton;
begin
  if Button = mbRight then
  begin
    PopupMenu := TdxBarPopupMenu.Create(Self);
    for I := 1 to ButtonCount do
    begin
      Buttons[I] := TdxBarButton.Create(Self);
      with Buttons[I] do
      begin
        Caption := Captions[I];
        if I < ButtonCount then ImageIndex := I;
        Tag := I;
        OnClick := PopupMenuButtonClick;
      end;
      with PopupMenu.ItemLinks.Add do
      begin
        BeginGroup := I = ButtonCount;
        Item := Buttons[I];
      end;
    end;
    PopupMenu.PopupFromCursorPos;
    for I := 1 to ButtonCount do
      Buttons[I].Free;
    PopupMenu.Free;
  end;
end;