I want to when Tform2 is created then show a message to user. I use this code, but not work well.
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;
That's because you declare a as a local variable. Each time you enter TForm1.Button1Click this variable will be brand new and uninitialized even though there might still be a Form2. That means that the check for nil won't even work.
You should either:
a a global (like the Form2 global you get when you first create a form)a part of the declaration of Form1 (you main form?) or a datamodule of other class that lives throughout your entire program. Screen.Forms to see if you got a Form2 in there.[edit]
Like this:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With