Show message when Tform2 is created?

不打扰是莪最后的温柔 提交于 2020-01-15 03:51:08

问题


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;

回答1:


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;



回答2:


The simplest possible solution to your problem is to use a global variable instead of a local variable, or to make your variable a field (an instance variable) in your class.

A global variable of type TForm2 is initialized automatically to nil, but as you found out above, the local variable, which is located on something called the "stack" is not.

You should read and learn about local and global variable scopes, and what the stack and the heap are. These are general concepts that apply in almost any programming language that is not completely "managed". In other words, you have to think about this in C and C++ as well as in Pascal.

Such things (uninitialized local variables, and access violations) are something that some languages (C# and java) protect you from, to some degree.



来源:https://stackoverflow.com/questions/4773052/show-message-when-tform2-is-created

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!