restrict window maximum size in secondary monitor

2019-08-15 20:41发布

I have a multi monitor setup. When a window is maximized on secondary monitor, I need to restrict the maximum size and position.

In MSDN, the documentation for MINMAXINFO mentions the following:

For systems with multiple monitors, the ptMaxSize and ptMaxPosition members describe the maximized size and position of the window on the primary monitor, even if the window ultimately maximizes onto a secondary monitor. In that case, the window manager adjusts these values to compensate for differences between the primary monitor and the monitor that displays the window. Thus, if the user leaves ptMaxSize untouched, a window on a monitor larger than the primary monitor maximizes to the size of the larger monitor.

So, I tried restriction by doing SetWindowPos in OnSysCommand if nId is SC_MAXIMIZE . It works, when the user clicks on maximize button/double click the title bar.

But, when the user uses Win+Up Arrow key or move the window to top of monitor to maximize, I am not able to handle the maximize restriction.

So, is there any common place to handle my all scenarios?

Is there any way to do trick on receiving WM_GETMINMAXINFO message.

标签: c++ mfc window
1条回答
该账号已被封号
2楼-- · 2019-08-15 20:58

I know this post is old, but I wish to share my code for those who still need a solution.

void CMyDialog::OnWindowPosChanging(WINDOWPOS * pos)
{
    //let us do the default processing first
    CDialogEx::OnWindowPosChanging(pos);

    //We are only interested in setting the window size when our window is in maximized state.
    //When maximized, the window will have a WS_MAIMIZE window style set
    LONG_PTR lWndStyle = GetWindowLongPtr(this->m_hWnd, GWL_STYLE);
    if ((lWndStyle & WS_MAXIMIZE) != WS_MAXIMIZE)
        return;

    //Use the proposed window from OS to identify the monitor.
    //I found that, the MonitorFromWindow() API returns primary monitor info when I restore a minimized window from taskbar.
    RECT rectWnd = {pos->x, pos->y, pos->x + pos->cx, pos->y + pos->cy};
    HMONITOR hMon = MonitorFromRect(&rectWnd, MONITOR_DEFAULTTONEAREST);

    MONITORINFO info;
    info.cbSize = sizeof(info);
    GetMonitorInfo(hMon, &info);

    LONG nMaxWndWidth = (info.rcWork.right - info.rcWork.left);
    LONG nMaxWndHeight = (info.rcWork.bottom - info.rcWork.top);

    //The window and workspace height can be > or <
    if (pos->cy != nMaxWndHeight)
    {
        pos->cy = nMaxWndHeight;
    }

    //The window and workspace width can be > or <
    if (pos->cx != nMaxWndWidth)
    {
        pos->cx = nMaxWndWidth;
    }
}
查看更多
登录 后发表回答