Why does AFXMessageBox process other messages first?

I have a MFC dialog based application, with a thread that monitors a serial port connection. To keep things simple though, here I'm just simulating data being sent back to back in this example.

If I call Thread2() it will post three messages, and for the sake of example, lets say all three get posted before TestFunction() gets called once, which is what I'm seeing, but I don't think it will always occur that way. Things worked great before I added an Afxmessagebox, but after, things got weird.

#define WM_TEST_MESSAGE WM_USER+9

bool ALERT_USER = true;

BEGIN_MESSAGE_MAP(CMyDlg, CDialogEx)
  ON_MESSAGE(WM_TEST_MESSAGE, TestFunction)
END_MESSAGE_MAP()


// On thread 1
LRESULT CMyDlg::TestFunction(WPARAM ch, LPARAM port)
{
  TRACE("Before AFX\n");

  if (ALERT_USER)
  {
    AfxMessageBox("About to disable alert!");
    ALERT_USER = false;
  }

  TRACE("After AFX\n");

  return 0;
}

// On thread 2
void Thread2()
{
  ::PostMessage(port->m_pOwner->m_hWnd, WM_TEST_MESSAGE, (WPARAM)0, (LPARAM)0);
  ::PostMessage(port->m_pOwner->m_hWnd, WM_TEST_MESSAGE, (WPARAM)0, (LPARAM)0);
  ::PostMessage(port->m_pOwner->m_hWnd, WM_TEST_MESSAGE, (WPARAM)0, (LPARAM)0);
}

This is what I expect to see:

Before AFX
About to disable alert!
After AFX
Before AFX
After AFX
Before AFX
After AFX

This is what I actually get:

Before AFX
Before AFX
Before AFX
About to disable alert!
After AFX
After AFX
After AFX
About to disable alert!
About to disable alert!

I found the best way to get my desired results is to swap the order of setting ALERT_USER to false with the message box, so that's not really an issue.

However, I really want to understand what is going on. Stepping through the code, my best guess is that AFXMessageBox is forcing everything else through the message queue before it will run.

Can anyone explain what AfxMessageBox is doing behind the scenes?

Answers


When you make a call to AfxMessageBox, it enters into message loop, and now WndProc can process new incoming messages. This is how MFC/Windows work - they keep on waiting for new messages (unless blocked). Note that displaying message box using [Afx]MessageBox is not blocking operation - it would rather enter into message-loop.

A Sleep call or a socket wait would be a blocking operation.


Need Your Help

Ada compiler not installed on this system error after make in Fedora 16

gcc ada fedora16

I installed gcc 4.3.4 fine one fedora16 but my problem is to run ada program got error Ada compiler not installed on this system. I think it crashes because of installed old version of gcc on gcc ...

ExtJS populate Ext.FormPanel with data from database (JSON)

javascript extjs extjs3 formpanel

I am using ExtJS (v3) and I have a form built that I want to populate so that a user can edit the data and then submit it back.