Search code examples
c++wxwidgets

How to correctly use wxID_OK and wxID_CANCEL?


There is a chart window which when right clicked shows a popup menu and then upon selection shows a window:

void CChart::Series_OnPopupMenu(wxCommandEvent& evt)
{
    int evtID = evt.GetId();


if (m_dlgManageSeriesData)
    return;


if(evtID==ID_ADDNEW) 
{
    m_dlgManageSeriesData=new dlgManageSeriesData(this);

    m_dlgManageSeriesData->Bind(wxEVT_CLOSE_WINDOW, &CChart::OnDlgManageSeriesDataClose, this);


    m_dlgManageSeriesData->Show();
}

To be able to track whether the shown window is closed or not:

void CChart::OnDlgManageSeriesDataClose(wxCloseEvent & evt)
{
    m_dlgManageSeriesData->Unbind(wxEVT_CLOSE_WINDOW, &CChart::OnDlgManageSeriesDataClose, this);

    m_dlgManageSeriesData = nullptr;

    evt.Skip();
}

The window, namely dlgManageSeriesData, have two buttons:

m_BtnOK = new wxButton(this, wxID_OK, "OK"); 

m_BtnCancel = new wxButton(this, wxID_CANCEL, "Cancel");

For example when Cancel button is clicked, simply it should close the window:

void dlgManageSeriesData::OnBtnCancelClick(wxCommandEvent & event)
{
    Close();
}

Few things happen on different scenarios:

1) If I dont attempt to manually close the window with dlgManageSeriesData::OnBtnCancelClick, then keeping wxID_CANCEL and clicking on Cancel button closes it as expected from wxDialog. However, it seems that closing the window in this fashion does not generate wxEVT_CLOSE_WINDOW as CChart::OnDlgManageSeriesDataClose is never called.

2) If I attempt to close the window with Close()while keeping wxID_CANCEL, the window never closes.

3) If I change the ID of the button and declare the cancel button as m_BtnCancel = new wxButton(this, wxID_ANY, "Cancel"); everything works as expected, such that cancel button closes the window and CChart::OnDlgManageSeriesDataClose is called. Similar rationale follows for the OK button.


Maybe I have misunderstood some concepts but couple questions:

1) Is wxWidgets' event handling system handles these IDs ( wxID_OK or wxID_CANCEL) differently such that it prevented the window from closing?

2) What is a good way of using wxID_OK and wxID_CANCEL if I still want to take some action when the window closes?

I am using wxWidgets 3.1.3 on Windows 10 with VS 2017.


Solution

  • wxWidgets does show wxID_OK and wxID_CANCEL specially in the dialogs by default and provides built-in logic for standard behaviour.

    However this shouldn't matter at all if you're not using wxDialog at all as you seem to be saying, although this is not totally clear. And, in fact, if you don't want to show it modally, there is no real reason to use wxDialog.

    If you really just create a normal wxFrame and call Close() from an event handler for one of its buttons, this should work independently of the ID you use for it.