c00000fd
c00000fd

Reputation: 22285

CDialog-based MFC application starts only in a primary monitor

Say, I am starting a CDialog-based MFC application from the Windows Explorer by double-clicking its executable file. It normally shows the dialog window in the center of the screen.

But if I move the Windows Explorer window into a secondary monitor and double-click it there, its window is still shown in the primary monitor.

How do I make it show in the monitor where the app is started from?

PS. The dialog window is shown from InitInstance as such:

CTestMFCDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();

Upvotes: 1

Views: 785

Answers (1)

c00000fd
c00000fd

Reputation: 22285

OK. I got it. Nevermind.

Whoever else is interested, MFC has no concept of multiple monitors. So one needs to override the centering method as such:

void CTestMFCDlg::CenterWindowSmart()
{
    //Try to get the monitor that the process was started in
    STARTUPINFO si = {0};
    ::GetStartupInfo(&si);
    MONITORINFO mi = {0};
    mi.cbSize = sizeof(mi);
    if(::GetMonitorInfo((HMONITOR)si.hStdOutput, &mi))
    {
        //Got monitor size & position where the process was started in
        CRect rcThis;
        this->GetWindowRect(rcThis);

        int x = ((mi.rcWork.right - mi.rcWork.left) - rcThis.Width()) / 2;
        int y = ((mi.rcWork.bottom - mi.rcWork.top) - rcThis.Height()) / 2;

        this->MoveWindow(mi.rcWork.left + x, mi.rcWork.top + y, rcThis.Width(), rcThis.Height());
    }
    else
        this->CenterWindow();
}

Based on the remarks for the STARTUPINFO structure (search for HMONITOR.)

Upvotes: 3

Related Questions