S
S
sorry_i_noob2019-06-09 18:39:49
Delphi
sorry_i_noob, 2019-06-09 18:39:49

What is the difference between TForm1.Button1.OnClick and Button1.OnClick? It's the same thing, but the first one doesn't work, and the second one does. Why?

Hello. There is such a code.

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure foo(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  (Sender as TButton).OnClick := foo; // работает
  (Sender as TButton).OnClick := TForm1.foo; // не работает

  Button1.OnClick := foo; // работает
  TForm1.Button1.OnClick := foo; // не работает
end;

procedure TForm1.foo(Sender: TObject);
begin
  MessageDlg('hello', mtError, mbOKCancel, 0);
end;

end.

I have a question. What is the difference in this code?
(Sender as TButton).OnClick := foo; // работает
(Sender as TButton).OnClick := TForm1.foo; // не работает

Button1.OnClick := foo; // работает
TForm1.Button1.OnClick := foo; // не работает

Why does one code work and another not?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AntHTML, 2019-06-10
@anthtml

Because TForm1.Button1.OnClick is a method of the TForm1 class
And Button1.OnClick is a method of the Form1
object

S
Stockholm Syndrome, 2019-06-09
@StockholmSyndrome

(Sender as TButton).OnClick := TForm1.foo;

this code does not work, because this way you can only call / get static methods of the class
, that is, it would work if it were like this:
TForm1 = class(TForm)
  Button1: TButton;
  class procedure foo(Sender: TObject);
  // ...

K
Konstantin Tsvetkov, 2019-06-09
@tsklab

(Sender as TButton).OnClick := Form1.foo; // заработает
  Form1.Button1.OnClick := foo; // заработает
procedure TForm1.foo(Sender: TObject);
begin
  ShowMessage( 'hello' );
end;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question