原文出处:
http://topic.youkuaiyun.com/t/20060729/23/4914257.html
原文摘要:
问题提出:
从MainForm动态创建一个Form(已经设计好的),代码为:
if (NOT Assigned(ActiveForm)) then
ActiveForm:= TActiveForm.Create(Application);
if(Assigned(ActiveForm)) then
ActiveForm.Show()
当调试运行后从ActiveForm的FormCreate()事件中直接使用Self.Close()关闭ActiveForm后,再次执行上述创建窗体的代码后发生错误, 并强制关闭。
解决方法:
在ActiveForm的FormCreate()事件中使用PostMessage来关闭窗体。代码:
Windows.PostMessage(Self.Handle, WM_CLOSE, 0, 0);
问题:
虽然关闭窗体的问题已经解决了,但是其中一些具体细节还不知道。为什么Self.Close()会发生错误,而 PostMessage()却可以正常执行 ? 为什么是第二次时发生错误而不是第一次时???
FormCreate()事件中一般会有一些初始化的代码,并且一个Form一般都会有一些组件,当从FormCreate()中直接 关闭时,是不是因为某些 组件未能正常初始化或释放而发生错误?如果这样理解的话,PostMessage()是不是提供了一个缓冲时间,来完成FormCreate()事件后再关闭Form?
精华代码:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFoo = class;
TForm2 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Foo: TFoo;
{ Private declarations }
public
{ Public declarations }
end;
TFoo = class(TComponent)
private
FForm:TForm;
function GetForm: TForm;
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
function TFoo.GetForm: TForm;
var S:String;
begin
if Assigned(FForm) then
Result := FForm
else
begin
FForm:=TForm.Create(nil);
Result:=FForm;
FForm.FreeNotification(Self);
end;
end;
procedure TFoo.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if(AComponent=FForm) and ( Operation = opRemove) then
begin
FForm:=nil
end;
end;
procedure TForm2.Button1Click(Sender: TObject);
var AForm:TForm;
begin
AForm:=Foo.GetForm;
AForm.ShowModal;
FreeAndNil(AForm);
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
Foo:=TFoo.Create(Self);
end;
procedure TForm2.FormDestroy(Sender: TObject);
begin
Foo.free;
end;
end.
本文探讨了在Delphi中动态创建窗体并在FormCreate事件中关闭窗体时遇到的问题及解决方案。通过对比Self.Close与PostMessage两种方法,分析了它们在窗体关闭时的行为差异及其背后的原因。
2万+

被折叠的 条评论
为什么被折叠?



