创建Tform2时显示消息? [英] Show message when Tform2 is created?

查看:69
本文介绍了创建Tform2时显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在创建Tform2时向用户显示一条消息。
我使用此代码,但效果不佳。

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;


推荐答案

这是因为您声明 a 作为局部变量。每次您输入 TForm1.Button1Click 时,即使可能仍然存在一个Form2,此变量也将是全新的且未初始化。

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.

您应该:


  • 使 a 成为全局变量(如首次创建表单时所获得的Form2全局变量)

  • 使<$ c Form1声明的$ c> a (您是主表单?)的一部分,还是贯穿整个程序的其他类的数据模块。

  • 根本不使用变量,而是检查 Screen.Forms 来查看是否有Form2。 li>
  • 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.

就像这样:

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;

这篇关于创建Tform2时显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆