2013-08-31 62 views
1

我試圖簡單地創建一個彈出菜單(或上下文菜單),添加一些項目,並在鼠標位置顯示它。我發現的所有例子都是用設計器來做的。我是通過一個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; 
+0

@Warren有靜態類型的語言,聲明一個變量足以初始化它。 C++就是一個明顯的例子。 –

+0

@喜歡期待插件DLL中的GUI代碼出現問題。 –

+0

-1代表「我的代碼顯然不起作用」。總是描述錯誤信息的失敗,逐字逐句複製 –

回答

6

在使用它們之前,您必須在Delphi中實際創建一個類的實例。以下代碼創建一個彈出式菜單,向其中添加一些項目(包括點擊的事件處理程序),並將其分配給表單。請注意,您必須像我所做的那樣自行聲明(並寫入)HandlePopupItemClick事件)。

在接口部分(添加Menususes條款):

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; 

現在我要把它留給你找出如何做休息(創建並在特定位置表現出來) 。

+0

我創建並顯示了所有相同過程中的上下文菜單。我不需要釋放任何正確的東西? – ikathegreat

+0

我無法回答,因爲我不知道你做了什麼。在我發佈的代碼中,菜單屬於表單方法(在表單方法中爲'TPopupMenu.Create(Self)',意味着表單是所有者,並且負責釋放它),並且各個項目屬於菜單('TMenuItem .Create(FPopup)')。您的菜單必須存在足夠長的時間才能使事件處理程序在單擊項目時仍然有效。 –

+1

我可能會做的是讓插件在其構造函數中創建彈出式菜單。然後,Execute將獲得光標位置並在該位置顯示菜單,插件的析構函數可以釋放彈出式菜單。我不知道這是否適用於您,因爲除了您在問題中發佈的內容之外,我沒有任何其他信息。 –

相關問題