Smash
Smash

Reputation: 3802

AfxMessageBox appears behind MFC dialog

In the main view of my application, I create a modeless dialog i.e.:

CMyDialog dlg;
int returnval = dlg.doModal();

Now this is the first time this happens to me, but in this particular dialog, if I want to display a message box on a button press, it always appears behind the dialog. If I press the alt key on the keyboard, then it gains focus and comes up front.

int nResult = AfxMessageBox(_T("Are you sure you want to delete this file?"), MB_YESNO|MB_ICONQUESTION|MB_SETFOREGROUND | MB_TOPMOST | MB_TASKMODAL);
if(nResult == IDNO){
    return;
}
else{
...
}

I am wondering what have I done or what option I checked that would result in this behaviour ?


EDIT: Here is the small portion of code in my OnInitDialog function, I commented out all the rest and the same behaviour remains:

CDialog::OnInitDialog();
DEVMODE sDevMode;
ZeroMemory(&sDevMode, sizeof(DEVMODE));
sDevMode.dmSize = sizeof(DEVMODE);

EnumDisplaySettings(NULL,ENUM_CURRENT_SETTINGS,&sDevMode);
_screenw = (int)sDevMode.dmPelsWidth;
_screenh = (int)sDevMode.dmPelsHeight;

_dlgx = (int) 50;
_dlgy = (int) 50;
_dlgw = (int) _screenw-100;
_dlgh = (int) _screenh-100;

this->MoveWindow(_dlgx,_dlgy,_dlgw,_dlgh);

Upvotes: 2

Views: 8498

Answers (4)

thierryc
thierryc

Reputation: 21

Thanks for the hint. Here's another form that work for me if you are not calling DoModal from the main window :

void MyApp::OnAppAbout()
{

    CAboutDlg aboutDlg;
    CWnd * pParent = GetMainWnd();
    if (pParent)
        pParent->PostMessage(WM_SYSKEYDOWN);

    aboutDlg.DoModal();
}

Upvotes: 0

Zac
Zac

Reputation: 4705

I was able to workaround this same issue by calling CWnd::PostMessage(0x118) before DoModal(), as reported here.

It seems a glitch in MFC architecture, as the dialog is not shown if the underlying message loop is not empty and the only way is to issue a 0x118 message or an ALT keypress (WM_SYSKEYDOWN).

So the workaround for this question could be:

CMyDialog dlg;
CWnd::PostMessage(0x118);
int returnval = dlg.doModal();

Upvotes: 5

Ajay
Ajay

Reputation: 18431

AfxMessageBox would always be modal on the top window in Z-order. I don't see any need to pass additional flags to bring it forward. Yes, if the application (main window) is not in focus, you may activate it explicitly before calling AfxMessageBox.

The only situation I see message-box not coming forward is when parent window is created by other thread, and AfxMessageBox is being called from another thread.

Upvotes: 0

rasmus
rasmus

Reputation: 3226

You can use MB_APPLMODAL to get it in front of all windows in your application.

What you should do is create the message box as a child of your dialog. Use CWnd::MessageBox for this.

Upvotes: 1

Related Questions