gpt4 book ai didi

delphi - 创建 Tform2 时显示消息?

转载 作者:行者123 更新时间:2023-12-03 18:08:50 25 4
gpt4 key购买 nike

我想在创建 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 的检查甚至不会起作用。

你应该:

  • 使 a 成为全局的(就像您第一次创建表单时获得的 Form2 全局一样)
  • 使 a 成为 Form1(您的主窗体?)或贯穿整个程序的其他类的数据模块声明的一部分。
  • 根本不要使用变量,而是检查 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;

关于delphi - 创建 Tform2 时显示消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4773052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com