我想在创建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;
Run Code Online (Sandbox Code Playgroud)
Gol*_*rol 10
那是因为你声明a为局部变量.每次输入TForm1.Button1Click此变量时,即使可能仍有Form2,也将是全新且未初始化的.这意味着检查nil甚至不起作用.
你应该:
a一个全局(就像第一次创建表单时获得的Form2全局)aForm1的声明(你主要形式?),或者贯穿生活整个程序的其他类的数据模块的一部分.Screen.Forms你是否有一个Form2.[编辑]
像这样:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |