在运行时创建弹出菜单

时间:2013-08-31 03:15:50

标签: delphi popup contextmenu

我正在尝试简单地创建一个弹出菜单(或上下文菜单),向其中添加一些项目,并在鼠标位置显示它。我发现的所有例子都是使用设计师完成的。我是从DLL插件做的,所以没有表单/设计器。用户将单击主应用程序中的一个按钮,该按钮调用下面的execute过程。我只想要一个类似于右键菜单的东西出现。

我的代码显然不起作用,但我希望在运行时而不是设计时创建一个弹出菜单。

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;

1 个答案:

答案 0 :(得分:7)

在使用它们之前,您必须在Delphi中实际创建类的实例。下面的代码创建一个弹出菜单,向其中添加一些项(包括单击的事件处理程序),并将其分配给表单。请注意,您必须像我已经完成的那样自己声明(并写入)HandlePopupItemClick事件。

在界面部分(将Menus添加到uses子句):

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;

现在,我将留给您了解如何完成其​​余工作(创建并在特定位置显示)。