txk2048
txk2048

Reputation: 315

wxWidgets app hanging when using modal dialog

I have a simple wxWidgets application where I create a wxMessageDialog and then show it.

For some reason when I return from the startup method the app will then hang.

Here is the code:

bool App::OnInit()
{
    wxMessageDialog* dialog = new wxMessageDialog(NULL, "Message", wxMessageBoxCaptionStr, wxOK | wxCENTER | wxDIALOG_NO_PARENT);
    dialog->ShowModal();

    return true;
}

I have tried calling EndModal() on the dialog but that makes no difference. I did see a question referencing this situation in Python but using wxDIALOG_NO_PARENT has made no difference to the behaviour

Any ideas what could the problem be?

Upvotes: 0

Views: 377

Answers (2)

VZ.
VZ.

Reputation: 22688

The application doesn't hang, it just runs waiting until someone tells it to exit. Usually it's done by the framework itself when the last window is closed, but as you don't have any windows (the dialog is closed before OnInit() returns and so doesn't count), this doesn't happen. I.e. this is working as expected, what exactly would you want to happen instead?

Also note that you have a memory leak in your code. Modal dialogs are one exception to the general rule of wxWidgets destroying all the objects you give to it and are not destroyed by the framework. This is because typically you don't need to destroy them at all because they're created on the stack and not on the heap:

    wxMessageDialog dialog(NULL, "Message", wxMessageBoxCaptionStr, wxOK | wxCENTER | wxDIALOG_NO_PARENT);
    dialog.ShowModal();

Upvotes: 1

rveerd
rveerd

Reputation: 4006

You have to create the application main window in App::OnInit() and you don't do that. If you don't create the main window, you must return false, not true.

The main window is usually a class derived from wxFrame. You can also use SetTopWindow() to let wxWidgets know what the main window is.

bool App::OnInit()
{
  if (someErrorCondition)
  {
    ::wxMessageBox("Oh no!");
    return false; // Return false if an error occurs and you cannot create the main window.
  }
  else
  {
    wxFrame* frame = new wxFrame(nullptr, wxID_ANY, "Amazing App");
    ::wxGetApp().SetTopWindow(frame); // Optionally set the main window.
    frame->Show(); // Optionally show our main window.
    return true; // Return true if all is well.
  }
}

Upvotes: 1

Related Questions