Search code examples
c++windowsmfcmessagebox

c++, mfc - messagebox display, main window has a cancel button. prevent cancel while messagebox is active


I have a queer sort of problem. Consider the following scenario:

  • Main window creates a child dialog on click of some button.
  • Child dialog does some task in a worker thread.
  • An error occurs during that task causing a message box to be displayed saying something along the lines of "Yikes! Something went wrong.".
  • Child dialog's 'Cancel' button is clicked on causing the child dialog to be closed.
  • Message box is still active! Clicking on anything in the message box = crash.

Pseudocode of how things are happening: (please ignore syntactic correctness here)

MainWindowClass mainObj;

void MainWindowClass::OnSomeButtonClick()
{
    SomeDialogClass someDialogObj;
    someDialogObj.DoModal();
}

int MainWindowClass::doTask()
{
    // Do work
    if(ERROR)
    {
        MessageBox("Yikes! Something went wrong.", "Error", MB_OK);
        return ERROR;
    }
} 

///////////////////////////////////////////////////////////////////
// Meanwhile, in another file,

extern MainWindowClass mainObj;

void SomeDialogClass::OnCancel()
{
    // Do all cleanup and close dialog
}

int SomeDialogClass::workerThreadFunc()
{
    return mainObj.doTask();
}

int SomeDialogClass::DoModal()
{
    AfxBeginThread(workerThreadFunc);
    // Do all other work and then wait for the worker thread
}

My question is twofold:

  1. On cancel, is there a way to know if any message boxes/dialogs in the same application are active?
  2. Is my entire design wrong and should I be doing something else altogether?

I thought one of the main reasons to use a modal dialog was its ability to prevent focus from going to parent dialogs. Yet, when that error message box is shown, I can happily click on the dialog and then click on 'Cancel' and pretend that the error message box never showed.


Solution

  • Rather than have your worker thread bring up a modal message box, it should signal the error condition back to the UI thread. My experience of MFC and multi-threading is that having all UI handled in the same thread makes things much simpler and removes these types of error. Having two threads potentially bringing up modal dialogs at the same time is asking for trouble.