有一个弹出式菜单附加到表单上的几个组件(按钮,但也像TCharts),我想知道哪个组件被右击以启动弹出菜单在第一个地方。
click方法的发送者参数仅指向TMenuItem,它是弹出菜单的父级(或父级菜单项)。
如何获取原始组件?
发布于 2020-07-18 22:00:53
我有一堆面板,我想让用户右键单击这些面板中的任何一个并执行“删除文件”操作。因此,我有一个弹出式菜单与所有这些面板相关联。这是我找出哪个面板被右键单击的方法:
(注意:我放了很多注释来清楚地解释它是如何工作的。但是如果你不喜欢它,你可以把代码压缩到2行(参见第二个过程)。
因此,如果您为该弹出菜单指定了操作:
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;https://stackoverflow.com/questions/2505831
复制相似问题