Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a popup menu at runtime

I'm trying to simply create a popup menu (or context menu), add some items to it, and show it at the mouse location. All the examples I have found are doing this using the designer. I'm doing this from a DLL plugin, so there is no form/designer. The user will click a button from the main application which calls the execute procedure below. I just want something similar to a right click menu to appear.

My code obviously doesn't work, but I was hoping for an example of creating a popup menu during runtime instead of design time.

procedure TPlugIn.Execute(AParameters : WideString);
var
  pnt: TPoint;
  PopupMenu1: TPopupMenu;
  PopupMenuItem : TMenuItem;
begin
  GetCursorPos(pnt);
  PopupMenuItem.Caption := 'MenuItem1';
  PopupMenu1.Items.Add(PopupMenuItem);
  PopupMenuItem.Caption := 'MenuItem2';
  PopupMenu1.Items.Add(PopupMenuItem);
  PopupMenu1.Popup(pnt.X, pnt.Y);

end;
like image 318
ikathegreat Avatar asked Dec 16 '22 06:12

ikathegreat


1 Answers

You have to actually create instances of a class in Delphi before you can use them. The following code creates a popup menu, adds a few items to it (including an event handler for the click), and assigns it to the form. Note that you have to declare (and write) the HandlePopupItemClick event yourself like I've done).

In the interface section (add Menus to the uses clause):

type
  TForm1 = class(TForm)
    // Double-click the OnCreate in the Object Inspector Events tab. 
    // It will add this item.
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    // Add the next two lines yourself, then use Ctrl+C to
    // generate the empty HandlePopupItem handler
    FPopup: TPopupMenu;      
    procedure HandlePopupItem(Sender: TObject);
  public
    { Public declarations }
  end;

implementation

// The Object Inspector will generate the basic code for this; add the
// parts it doesn't add for you.
procedure TForm1.FormCreate(Sender: TObject);
var
  Item: TMenuItem;
  i: Integer;
begin
  FPopup := TPopupMenu.Create(Self);
  FPopup.AutoHotkeys := maManual;
  for i := 0 to 5 do
  begin
    Item := TMenuItem.Create(FPopup);
    Item.Caption := 'Item ' + IntToStr(i);
    Item.OnClick := HandlePopupItem;
    FPopup.Items.Add(Item);
  end;
  Self.PopupMenu := FPopup;
end;

// The Ctrl+C I described will generate the basic code for this;
// add the line between begin and end that it doesn't.
procedure TForm1.HandlePopupItem(Sender: TObject);
begin
  ShowMessage(TMenuItem(Sender).Caption);
end;

Now I'll leave it to you to figure out how to do the rest (create and show it at a specific position).

like image 197
Ken White Avatar answered Dec 27 '22 17:12

Ken White