弹出菜单单击源自哪个组件

时间:2010-03-24 06:47:32

标签: delphi contextmenu

将弹出菜单附加到表单上的多个组件(按钮,还有TCharts之类的东西),我想知道哪个组件被右键单击以首先启动弹出菜单。

click方法的Sender参数只指向TMenuItem,它是弹出菜单(或育儿菜单项)的父级。

如何获取原始组件?

5 个答案:

答案 0 :(得分:35)

您的意思是PopupMenu1.PopupComponent吗?

答案 1 :(得分:10)

您可以通过

获取PopupMenu的TMenuItem的click事件中的调用者组件
Caller := ((Sender as TMenuItem).GetParentMenu as TPopupMenu).PopupComponent;

分配给多个列表框并解决导出到文件功能的PopupMenu示例:

procedure TForm1.mniExportFileClick(Sender: TObject);
var Caller: TObject;
begin  
  if SaveTextFileDialog1.Execute then
  begin
    Caller := ((Sender as TMenuItem).GetParentMenu as TPopupMenu).PopupComponent;
    (Caller as TListBox).Items.
      SaveToFile(SaveTextFileDialog1.FileName,
        StandardEncodingFromName(
          SaveTextFileDialog1.Encodings[SaveTextFileDialog1.EncodingIndex]));
  end;
end; 

答案 2 :(得分:0)

作为最后的手段,您可以使用Mouse.CursorPos中的TPopupMenu.OnPopup在表单上查找此组件。但可能有更好/更简单的方法。

答案 3 :(得分:0)

PopUpMenu.PopupComponent表示响应鼠标右键单击最后显示弹出菜单的组件

答案 4 :(得分:0)

我有一堆面板,我想让用户右键单击任何一个面板并执行“删除文件”操作。 因此,我有一个与所有这些面板关联的弹出菜单。 这是我找出右键单击哪个面板的方法:

(注意:我发表了很多评论来清楚地解释它是如何工作的。但是,如果您不喜欢它,可以将代码压缩为两行(请参阅第二个过程)。)

因此,如果您已将操作分配给该弹出菜单:

procedure Tfrm.actDelExecute(Sender: TObject);
VAR
  PopMenu: TPopupMenu;
  MenuItem: TMenuItem;
  PopupComponent: TComponent;
begin
 { Find the menuitem associated to this action }
 MenuItem:= TAction(Sender).ActionComponent as TMenuItem;  { This will crash and burn if we call this from a pop-up menu, not from an action! But we always use actions, so.... }

 { Was this action called by keyboard shortcut? Note: in theory there should be no keyboard shortcuts for this action if the action can be applyed to multiple panels. We can call this action ONLY by selecting (right click) a panel! }
 if MenuItem = NIL then
  begin
   MsgError('This action should not be called by keyboard shortcuts!');
   EXIT;
  end;

 { Find to which pop-up menu this menuitem belongs to }
 PopMenu:= (MenuItem.GetParentMenu as TPopupMenu);

 { Find on which component the user right clicks }
 PopupComponent := PopMenu.PopupComponent;

 { Finally, access that component }
 (PopupComponent as TMonFrame).Delete(FALSE);
end;

如果您只有一个简单的弹出菜单(未分配操作):

procedure Tfrm.actDelHddExecute(Sender: TObject);
VAR PopupComponent: TComponent;
begin
 PopupComponent := ((Sender as TMenuItem).GetParentMenu as TPopupMenu).PopupComponent;
 (PopupComponent as TMonFrame).Delete(TRUE);
end;

您可以将所有代码放在一个返回TPanel的单个函数中,并像这样调用它:

procedure Tfrm.actDelWallExecute(Sender: TObject);
begin
 if GetPanelFromPopUp(Sender) <> NIL
 then GetPanelFromPopUp(Sender).Delete(FALSE);
end;