Link to home
Start Free TrialLog in
Avatar of boardtc
boardtcFlag for Ireland

asked on

Attach a function to an event handler

How can I attach a function which is declared in another unit to an event handler, say OnDoubleClick. It seems what you attach in code must be declared in the class (published section).

Thanks,

Tom.
Avatar of ZifNab
ZifNab

I think this is what you want,

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

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

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
 Form2.ShowModal;
end;

procedure TForm1.WriteHallo;
begin
 label1.Caption := 'Hello, Tom is this what you want?';
end;

end.

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ExtCtrls, StdCtrls;

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

var
  Form2: TForm2;

implementation

uses Unit1; { <-------- THIS NEEDS TO BE HERE }

{$R *.DFM}

procedure TForm2.Button1Click(Sender: TObject);
begin
 {Add Unit1 to uses list}
 Form1.WriteHallo;
end;

end.

Avatar of boardtc

ASKER

?? I don't follow what you are trying.

What i want to do in thre form create is:

TPanel.OnDblClick := MyFunction;

where my function is a function declared in another unit.

Thanks,

Tom.
Ah, now I get it.
But my solution works too. If you push the button in Form2 then in Form1 the text in caption1 will be changed (thanks to procedure WriteHallo) -> look at form1 after pushing button on form2.

If you put in your TPanel.OnDblClick the following code :
FormName.FunctionName then this will be activated when you double click on tpanel. This is the easiest way to do it.
Avatar of boardtc

ASKER

Ok, the later makes sense, I'll do it that way, I should have thought of that. Put an answer in so I can grade you. Tom.
ASKER CERTIFIED SOLUTION
Avatar of ZifNab
ZifNab

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of boardtc

ASKER

calling the function in a handler was the way to go rather than trying to attach to the handler.