请问一个关于两个窗体切换的问题,谢谢!
我写了个程序,一共有三个窗体,Form1、Form2、Form3,其中Form2为登录框,Form1和Form3是两个独立的窗体,分别有自己独立的程序。我想实现,从登录框Form2登录后,根据条件,会打开Form1和Form3中的一个窗体,另一个窗体不会打开,也不被创建。在Form1和Form3的界面上各有一个按钮button,他的用处是把当前的窗体关闭掉,是真正的关闭,不是隐藏起来,然后创建打开另一个窗体。相关代码段如下:
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Form2=new TForm2(Application);
if(Form2->ShowModal()!=mrOk)
{
delete Form2;
Application->Terminate();
return 0;
}
else
{
delete Form2;
Form2=NULL;
}
if(Form1->ShowModal()==mrOk)
{
delete Form1;
Form1=NULL;
Application->CreateForm(__classid(TForm3), &Form3);
}
if(Form3->ShowModal()==mrOk)
{
delete Form3;
Form3=NULL;
Application->CreateForm(__classid(TForm1), &Form1);
}
//Application->CreateForm(__classid(TForm1), &Form1);
//Application->CreateForm(__classid(TForm3), &Form3);
Application->Run();
}
-----------------------
Unit1.cpp
void __fastcall TForm1::Button129Click(TObject *Sender)
{
ModalResult=mrOk;
}
-----------------------
Unit3.cpp
void __fastcall TForm3::Button26Click(TObject *Sender)
{
ModalResult=mrOk;
}
我也试用Form1->close();但他会将Form3也一起关掉。我也试过把Application->CreateForm(__classid(TForm1), &Form1);加入到Unit3.cpp中,还试过很多办法,但是包括上面贴出的代码段都是编译能通过,执行就会出Debugger Exception Notification的错误框。希望各位高手能够指点一下小弟,不胜感激,谢谢!
[解决办法]
说个笨办法吧:
创建一个主窗体,在主窗体中创建一个新线程,新线程中分别调用Form1和Form3,根据ShowModal的结果来判定是否调用另一个窗体,如:
TFormMain::TFromMain() { ThreadControl *thread = new ThreadControl(); thread->WaitFor(); delete thread; Application->Terminate();}class ThreadControl : public TThread {private: int m_idAction; ......};ThreadControl::Execute() { m_idAction = ACTION_SHOW_FORM1; while ( m_idAction != ACTION_EXIT ) { switch ( m_idAction ) { case ACTION_SHOW_FORM1 : Synchronize(ShowForm1); break; case ACTION_SHOW_FORM3 : Synchronize(ShowForm3); break; } }}void __fastcall ThreadControl::ShowForm1() { TForm1 *form = new TForm1(...); form->ShowModal(); m_idAction = form->NextAction(); delete form;}TForm1::bnOkClick(TObject *Sender) { switch ( status ) { case ..... m_idNextAction = ACTION_SHOW_FORM3; break; case .... m_idNextAction = ACTION_EXIT; } ModalResult = mrOk;}TForm1::NextAction() { return m_idNextAction;}
[解决办法]
主窗体是谁?主窗体关闭了,程序也就关闭了,可以新增加一个主窗体,在登陆后创建主窗体,再根据条件创建form1或者form3