c++c++buildervclrad-studio

How to close a C++ VCL form and open another one on a button click?


I'm having trouble closing Form1 and opening Form3 through a button click.

I have tried this code:

#include "Welcome.h"
#include "Login.h"

void __fastcall TForm1::LoginButtonClick(TObject *Sender)
{
    TForm1 *CurrentForm = new TForm1(this);
    CurrentForm->Close();
    TForm3 *NewForm = new TForm3(this);
    NewForm->Show();
}

This is the part of the code that is not working:

TForm1 *CurrentForm = new TForm1(this);
CurrentForm->Close();

What can I change to make Form1 close upon the button click?


Solution

  • Get rid of CurrentForm. You are creating a whole new Form object just to close it immediately. You need to instead call Close() on the Form object that the button belongs to. And since the OnClick handler is a method of that Form, you can simply use the method's this pointer to access the Form object, eg:

    void __fastcall TForm1::LoginButtonClick(TObject *Sender)
    {
        Close(); // aka this->Close()
        TForm3 *NewForm = new TForm3(this);
        NewForm->Show();
    }
    

    Just be aware that TForm1 is usually the default name of the MainForm, and if you Close() the MainForm then your app will exit. If you need to "close" the MainForm without exiting the app, you can Hide() the MainForm instead.