I made 2 form. MainForm and ChildForm(I set become available forms)
design >> https://i.sstatic.net/R4XWf.png
when I want to call my ChildForm use this code
void __fastcall TMainForm::ChildForm1Click(TObject *Sender)
{
if(!ChildForm)
{ ChildForm = new TChildForm(this); }
else
{ ChildForm->WindowState=wsNormal; }
}
and to close
void __fastcall TChildForm::FormClose(TObject *Sender,
TCloseAction &Action)
{
Action=caFree;
}
why when i open ChildForm then i close. and when to open again . ChildForm Can't open ??
#Main Form
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "Unit2.h" //ChildForm
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMainForm *MainForm;
//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::ChildForm1Click(TObject *Sender)
{
if(!ChildForm)
{ ChildForm = new TChildForm(this); }
else
{ ChildForm->WindowState=wsNormal; }
}
As it has been discussed in the comments, and thanks to the help of @Remy Lebeau, in the TMainForm
class, you need to set the ChildFrom
pointer to NULL
after having destroyed the form it points to. This may be accomplished in the destructor of the TChildForm
class, by using the pointer of its owner that has been passed to it at construction time.
The issue is basically in that code snippet:
if(!ChildForm)
{ ChildForm = new TChildForm(this); }
else
{ ChildForm->WindowState=wsNormal; }
The first time, everything works as planned. When ChildForm
is destroyed however, the pointer isn't reset, and the next time ChildForm
creation is requested, the first test fails, and of course the form isn't created.
So:
make the TChildForm
class keep a copy of its owner's pointer (you'll probably need to change the constructor prototype to the following:
__fastcall TChildForm::TChildForm(TMainForm *owner)
in order for TChildForm
to know the full type of its owner (the IDE should #include
the TMainForm
header for you, or ask for the permission to do it).
Create a method in TMainForm
to handle TChildForm
pointer reset, and give it the right access level for a TChildForm
to invoke it.
add a call to that method (ie. owner->onChildFormTermination()
or something like that) in ~TChildForm
to let its owner know.
Note that my VCL-fu is a bit rusty (I haven't coded with C++Builder for 10+ years), there might be a more idiomatic way of writing this.