一个困扰我二天的问题解决了,心里非常高兴。现将代码拿出来共享如(兄弟水平很低)如有更好的方法请和我联系
QQ:14564807
一个关于主从窗体的程序的示例,从窗体显示在主窗体的pagecontrol上,
难点:打开关闭后再打开就出错
原因:Form.free后指针不为NIL所以用 if not Assigned(form3) then
判断出错,
解决方法:使用Stringlist动态跟踪Form的创建情况。
/////////////////////////////////////////
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, Menus, StdCtrls, Buttons;
type
TForm1 = class(TForm)
tlb1: TToolBar;
btn1: TToolButton;
btn2: TToolButton;
pgc1: TPageControl;
lbl1: TLabel;
lbl2: TLabel;
pm1: TPopupMenu;
N1: TMenuItem;
lst1: TListBox;
procedure btn1Click(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure pgc1MouseDown(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Tabsheet:TTabSheet;
Index: Integer;
Formlist:TStringList;
implementation
{$R *.dfm}
uses Unit2,unit3;
procedure TForm1.btn1Click(Sender: TObject);
var
i:Integer;
begin
if Formlist.IndexOf('Form2')<0 then
//if not Assigned(form2) then
begin
tabsheet:=TTabSheet.Create(nil);
Tabsheet.PageControl:=pgc1;
form2:=Tform2.Create(nil);
Tabsheet.Caption:=Form2.Caption;
Tabsheet.Name:='Form2';
Formlist.Add('Form2');
lst1.Items:=Formlist;
Form2.Parent:=Tabsheet;
Form2.Show;
end;
For i:=0 to pgc1.PageCount-1do
if pgc1.Pages.Name='Form2' then
begin
pgc1.Pages.TabVisible:=True;
pgc1.ActivePage:=pgc1.Pages;
Exit;
end;
end;
procedure TForm1.N1Click(Sender: TObject);
begin
Formlist.Delete(Formlist.IndexOf(pgc1.Pages[Index].Name));
pgc1.Pages[Index].Free;
lst1.Items:=Formlist;
end;
procedure TForm1.btn2Click(Sender: TObject);
var
i:Integer;
begin
if Formlist.IndexOf('Form3')<0 then
//if not Assigned(form3) then
begin
tabsheet:=TTabSheet.Create(nil);
Tabsheet.PageControl:=pgc1;
Form3:=TForm3.create(NIL);
Tabsheet.Name:='Form3';
Tabsheet.Caption:=Form3.Caption;
Formlist.Add('Form3');
lst1.Items:=Formlist;
Form3.Parent:=Tabsheet;
Form3.Show;
end;
For i:=0 to pgc1.PageCount-1do
if pgc1.Pages.Name='Form3' then
begin
pgc1.Pages.TabVisible:=True;
pgc1.ActivePage:=pgc1.Pages;
Exit;
end;
end;
procedure TForm1.pgc1MouseDown(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
begin
if (Button = mbLeft) and (ssDouble in Shift) then
begin
Index :=pgc1.IndexOfTabAt(X, Y);
if Index >= 0 then
begin
Formlist.Delete(Formlist.IndexOf(pgc1.Pages[Index].Name));
pgc1.Pages[Index].Free;
lst1.Items:=Formlist;
end
end
else
begin
if Button=mbRight then
begin
Index :=pgc1.IndexOfTabAt(X, Y);
if Index >= 0 then
pm1.Popup(Mouse.CursorPos.x,Mouse.CursorPos.y);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FormList:=TStringList.Create;
end;
end.
代码付上: