Delphi中動態創建窗體有四種方式


Delphi中動態創建窗體有四種方式,最好的方式如下:

比如在第一個窗體中調用每二個,主為第一個,第二個設為動態創建

Uses Unit2; //引用單元文件

procedure TForm1.Button1Click(Sender: TObject);
begin
form2:=TForm2.Create(Application); //創建窗體
form2.Show; //顯示窗體
end;
end.

======================================================

最好不要用另外三種:

Application.CreateForm(TForm2,Form2);

form2:=TForm2.Create(Self);

form2:=TForm2.Create(nil);

 

 

Delphi窗體創建大揭密

1. 窗體權限的轉移實驗

新建3個Form , 在Project->Options… 中的Forms 一頁把Form2和Form3 放置在 Available forms中,保留Form1在Auto-create forms中,讓Form1在程序一開始運行就創建。

在Form1(主窗體)中的OnCreate()事件函數中加入以下代碼:

procedure TForm1.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form1 Create Completed!;

Form1.Show;

Application.CreateForm(TForm2, Form2);

end;

(代碼2)

在Form2的OnCreate()事件函數中加入以下代碼:

procedure TForm2.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form2 Create Completed!;

Form2.Show;

Application.CreateForm(TForm3,Form3);

end;

(代碼3)

在Form3的OnCreate()事件函數中加入以下代碼:

procedure TForm2.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form3 Create Completed!;

Form3.Show;

end;

(代碼4)

這個程序在運行后將顯示三個窗體,分別是Form1,Form2,和Form3。你可能在想,如果要關閉程序,只要關閉Form1這個主窗體就可以了。然而你錯了,應該是關閉Form3才能將整個程序關閉。為什么呢?關鍵在CreateForm()這個窗體創建函數,查一下Delphi的隨機幫助文件就清楚了。幫助文件有關CreateForm()函數的說明如下:


Call CreateForm to dynamically create a form at runtime. Developers do not need to add code for creating most forms, because typically one or more calls to CreateForm are added automatically to the projects main source when using the form designer.


CreateForm creates a new form of the type specified by the FormClass parameter and assigns it to the variable given by the Reference parameter. The owner of the new form is the Application object.


Note: By default, the form created by the first call to CreateForm in a project becomes the application’s main form.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM