How can a generic event handler find out which control event it is handling?

I want to write code that assigns the same event handler to several different buttons. Is there a way to implement it without referring to each button by name, but using something in common, such as self or sender, to reference the button?

+3
source share
4 answers

Yes. Each call to the normal method includes a hidden "I" that refers to the object. But in the event handler, "I" is a form, not a button. The "Sender" button, and you have to resort to its type, using something like Sender as TButton.

+3

.

(Sender as TButton).Enabled := False;

, onclick.

TButton(Sender).Enabled := False;

100%, . , , , , .

+2

- :

procedure OnClickButton(Sender: TObject);
var btn: TButton;
begin
  if Sender is TButton then btn := TButton(mycontrol) 
  else
      exit;
  //and then use btn as just another button control
end;

, :

if mycontrol is TButton then 
  TButton(mycontrol).OnClick := OnClickButton;
+1

"" . Plonk , "" . , ( , ), OnExecute . , "" . , .

? : 1. , , , , TPopupMenu. 2. , . 3. , "OnUpdate" - :

procedure TForm1.MyActionOnUpdate( ASender : TObject );
begin
  With Sender as TAction do
    Enabled := ItsPossibleToRunMyCode;
end;

This bit of code will enable and disable any control that uses this action without requiring anything.

0
source

Source: https://habr.com/ru/post/1725473/


All Articles