Search code examples
c++wxwidgets

How can Close wxDialog in wxWidget?


I spent many hours studying the problem How to Close app what i build form wxDialog I create two button OK and Exit, when i press Exit or sign [X] signal of App then i issue this error

Error image: enter image description here

  // The Queue of Event Table

    BEGIN_EVENT_TABLE(AutoPokemonDlg, wxDialog)
    EVT_BUTTON(wxID_OK, AutoPokemonDlg::OnOK)
    EVT_BUTTON(wxID_EXIT, AutoPokemonDlg::OnExit)
    EVT_CLOSE(AutoPokemonDlg::OnCloseWindow)
    END_EVENT_TABLE()


    // I create Event Handler

    void AutoPokemonDlg::OnExit(wxCommandEvent& WXUNUSED(event))
    {
        Close(true);
    }

    void AutoPokemonDlg::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
    {
        Destroy();
    }

    and main Window, i use wxDialog to inherit my subclass is AutoPikachuDlg
    ////AutoPokemonDlg.h
    class AutoPokemonDlg : public wxDialog
    {
    public:
        // Constructor
        AutoPokemonDlg(wxWindow* parent, const wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size);
        ~AutoPokemonDlg();
        // Event handlers
        void OnOK(wxCommandEvent& event);
        void OnExit(wxCommandEvent& WXUNUSED(event));
        void OnCloseWindow(wxCloseEvent& event);

    protected:
    private:
        DECLARE_EVENT_TABLE()
    };

    //////AutoPokemonDlg.cpp
    AutoPokemonDlg::AutoPokemonDlg(wxWindow* parent, const wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size)
        : wxDialog(parent, id, title, pos, size)
    {
    //...
    };

Solution

  • You don't show how do you create and show your AutoPokemonDlg, but if you do it on stack, as recommended, e.g. like this:

    void SomeEventHandler(wxEvent&) {
        AutoPokemonDlg dialog(...);
        dialog.ShowModal();
    }
    

    then your code will result in calling delete &dialog which is clearly wrong, as this is not a heap pointer. This happens because you call Destroy() from your OnCloseWindow() handler -- it can't be used for modal dialogs for exactly this reason.

    The simplest fix is to just remove your OnCloseWindow() handler entirely, it's usually unnecessary as the dialog will close anyhow if it has any buttons that can be used for closing it, such as wxID_OK or wxID_CANCEL. If it doesn't close on its own for you, it might be because you do something strange in your OnCloseWindow::OnOk() (which you don't show neither). If you want it to close your dialog, call EndModal() to do it from there.