我想在创建 Tform2 时向用户显示一条消息。
我使用这段代码,但效果不好。
procedure TForm1.Button1Click(Sender: TObject);
var
a:TForm2;
begin
if a=nil then
begin
a := TForm2.Create(Self);
a.Show;
end
else
begin
showmessage('TForm2 is created');
end;
end;
那是因为你声明a
作为局部变量。每次你进入TForm1.Button1Click
即使可能仍然存在 Form2,该变量也将是全新且未初始化的。这意味着对 nil 的检查甚至不起作用。
您应该:
- Make
a
全局(就像您第一次创建表单时获得的 Form2 全局)
- Make
a
Form1(您的主窗体?)或存在于整个程序中的其他类的数据模块的声明的一部分。
- 根本不使用变量,但检查
Screen.Forms
看看里面是否有 Form2。
[edit]
像这样:
var
i: Integer;
begin
// Check
for i := 0 to Screen.FormCount - 1 do
begin
// Could use the 'is' operator too, but this checks the exact class instead
// of descendants as well. And opposed to ClassNameIs, it will force you
// to change the name here too if you decide to rename TForm2 to a more
// useful name.
if Screen.Forms[i].ClassType = TForm2 then
begin
ShowMessage('Form2 already exists');
Exit;
end;
end;
// Create and show.
TForm2.Create(Self).Show;
end;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)