When a TAction event fires, the "Sender" is always the action itself. Usually that's the most useful, but is it somehow possible to find out who triggered the action's OnExecute event?
Example
Let's say you have a form with the following:
Button1
and Button2
actDoStuff
The same action is assigned to both buttons. Is it possible to show which button I clicked?
Example.dfm
object Form1: TForm1
object Button1: TButton
Action = actDoStuff
end
object Button2: TButton
Action = actDoStuff
Left = 100
end
object actDoStuff: TAction
Caption = 'Do Stuff'
OnExecute = actDoStuffExecute
end
end
Example.pas
unit Example;
interface
uses Windows, Classes, Forms, Dialogs, Controls, ActnList, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
actDoStuff: TAction;
procedure actDoStuffExecute(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.actDoStuffExecute(Sender: TObject);
begin
ShowMessage('Button X was clicked');
end;
end.
The only solution I see at the moment is to not use the action property of buttons, but having an eventhandler for each button, and calling actDoStuffExecute() from there, but that sort of defies the whole purpose of using actions in the first place.
I don't want to have a dedicated action for each separate control either. The example above is a simplified version of the problem that I'm facing. I have a menu with a variable number of menu items (file names), and each menu item basically has to do the same thing, except for loading another file. Having actions for each menu item would be a bit silly.
Try using the ActionComponent property:
Stores the client component that caused this action to execute.
Use ActionComponent to discern which client component caused this action to execute. For example, examine ActionComponent from an OnExecute event handler if you need to know what user action triggered this action.
When the user clicks a client control, that client sets ActionComponent before calling the action's Execute method. After the action executes, the action resets ActionComponent to nil.
For example:
ShowMessage( (Sender as TAction).ActionComponent.Name );
Using this I get "Button1" and "Button2" when I click the first and second button respectively.