procedure FormShow(Sender: TObject);
begin
//自定义的代码
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2 := TForm.Create(nil);
Form2.Caption := 'Hello Caption';
Form2.BorderStyle := bsDialog;
Form2.Position := poScreenCenter;
Form2.OnShow := //问题就在这里,如何让动态创建的窗口Form2,在Show的时候调用上面的FormShow函数? Form2.ShowModal;
Form2.Free;
end;
begin
//自定义的代码
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2 := TForm.Create(nil);
Form2.Caption := 'Hello Caption';
Form2.BorderStyle := bsDialog;
Form2.Position := poScreenCenter;
Form2.OnShow := //问题就在这里,如何让动态创建的窗口Form2,在Show的时候调用上面的FormShow函数? Form2.ShowModal;
Form2.Free;
end;
begin
//自定义的代码
end;
把这个过程要定义到类里面。不能是一般普通的过程。
*************************************
When you are creating components at run time, and want to assign a procedure to an event handler of a component, like in the following code:
procedure ButtonClick(Sender:TObject) ;
begin
//whatever
end;procedure SomeProcedure...
var aButton:TButton;
begin
aButton := TButton.Create(nil) ;
aButton.OnClick = ButtonClick
...
end;You will get the next error:
Incompatible type: 'method pointer and regular procedure'.The problem is that a method pointer (OnClick) needs to be a procedure of an object (like TForm), not a regular procedure.One way around is to create an object to define the procedure. You can start by creating a dummy class...interfacetype
TEventHandlers = class // create a dummy class
procedure ButtonClick(Sender: TObject) ;
end;...var EvHandler:TEventHandlers;implementationprocedure TEventHandlers.ButtonClick(Sender: TObject) ;
begin
// your code here
end;...
procedure SomeProcedure...
var aButton:TButton;
begin
aButton := TButton.Create(nil) ;
aButton.OnClick = ButtonClick;
...
end;This compiles!
}
楼主的代码编译通过,未做测试
begin
Form2 := TForm.Create(nil);
Form2.Caption := 'Hello Caption';
Form2.BorderStyle := bsDialog;
Form2.Position := poScreenCenter;
Form2.OnShow := Form2_Show;//问题就在这里,如何让动态创建的窗口Form2,在Show的时候调用上面的FormShow函数? Form2.ShowModal;
Form2.Free;
end;procedure TForm1.Form2_Show(Sender: TObject);
begin
showmessage((Sender as TForm).Caption);
end;
-----------------------
unit Unit2;interfaceuses
Forms, Classes, SysUtils;type
TMyForm = class(TForm)
private
FMyShow: TNotifyEvent;
protected
procedure DoShow; override; //重载TForm类中的DoShow方法
published
property OnMyShow: TNotifyEvent read FMyShow write FMyShow;
end;implementation{ TMyForm }procedure TMyForm.DoShow;
begin
inherited;
if Assigned(FMyShow) then FMyShow(self);
end;end.2. Form2从TMyForm继承下来3. Form1中创建Form2procedure FormShow(Sender: TObject);
begin
//自定义的代码
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2 := TForm.Create(nil);
Form2.Caption := 'Hello Caption';
Form2.BorderStyle := bsDialog;
Form2.Position := poScreenCenter;
Form2.OnMyShow := FormShow; //事件赋值
Form2.ShowModal;
Form2.Free;
end;
[Error] Unit1.pas(38): Undeclared identifier: 'OnMyShow'
这句报错
已经引用unit2
TForm2 = class(TForm)修改成type
TForm2 = class(TMyForm)