Should be simple enough but I can't see it.
You can find out the component that was right-clicked on to display a popup menu with:
PopupMenu1.PopupComponent
but how do you find out the popup menu that contains the TMenuItem that was in turn clicked on that menu?
To simplify the problem to an example:
I have a series of labels, each with a different caption, and I have a popup menu that is assigned to the PopupMenu property of each of the labels.
When someone right-clicks one of the labels and brings up the popup menu, and then clicks on MenuItem1, I want to code:
procedure TForm1.MenuItem1Click(Sender: TObject);
begin
MsgBox (Format ('The label right-clicked has the caption %', [xxxx.Caption ])) ;
end ;
What should xxxx be?
Implemented Answer
Thanks to both respondents. What I ended up with was this:
procedure TForm1.MenuItem1Click(Sender: TObject);
var
AParentMenu : TMenu ;
AComponent : TComponent ;
ALabel : TLabel ;
begin
AParentMenu := TMenuItem (Sender).GetParentMenu ;
AComponent := TPopupMenu (AParentMenu).PopupComponent ;
ALabel := TLabel (AComponent) ;
MsgBox (Format ('The label right-clicked has the caption %', [ALabel.Caption ])) ;
end ;
which also interrogates which TMenuItem was involved and therefore gives me a fragment of code I can drop into other OnClick handlers with less modification.
I'm a little confused by your question but since you've ruled out everything else I can only imagine you are looking for TMenuItem.GetParentMenu
.
procedure TForm1.MenuItem1Click(Sender: TObject);
var pop:TPopupMenu;
lbl:TLabel;
begin
// Firstly get parent TPopupMenu (needs casting from TMenu)
pop:= TPopupMenu(MenuItem1.GetParentMenu());
// pop.PopupComponent is the "source" control, just cast it to Tlabel
lbl:= TLabel(pop.PopupComponent);
ShowMessage(Format('The label right-clicked has the caption %s',[lbl.Caption]));
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With