Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show message when Tform2 is created?

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;
like image 606
User Avatar asked Mar 22 '26 20:03

User


1 Answers

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:

  • Make a a global (like the Form2 global you get when you first create a form)
  • Make a part of the declaration of Form1 (you main form?) or a datamodule of other class that lives throughout your entire program.
  • Don't use a variable at all, but check 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;
like image 136
GolezTrol Avatar answered Mar 25 '26 14:03

GolezTrol