一个更好的CenterWindow()函数

下载演示项目- 42.2 kb图1。主CenterSample程序示例屏幕。 介绍 定心窗口在屏幕上是你通常可以做的 CWnd::CenterWindow()函数在MFC。CenterWindow () 获取一个指向CWnd的指针作为参数,并且假定是函数 是否会将调用它的窗口的中心与传递它的窗口相对 一个指针: 隐藏,复制Code

pDlg->CenterWindow(AfxGetMainWnd()); // Centers pDlg against the main window?

清单1。演示使用CWnd::CenterWindow()将对话框居中。 然而,一个问题向MFC邮件列表提出 最近被问到,“我有一个基于对话框的程序,用户可以点击一个按钮和 弹出子对话框。如果我调用CWnd::CenterWindow()在子对话框的 OnInitDialog()处理程序,对话框将始终居中 屏幕的,不居中于主对话框。我该怎么做呢?” 所以我想出了一个“强力”定心功能,它实际上工作得更好 比CWnd: CenterWindow()。它被称为 CenterWindowOnOwner(),我添加到我的示例程序的 CSubDialog sub-dialog的类: 隐藏,收缩,复制Code

void CSubDialog::CenterWindowOnOwner(CWnd* pWndToCenterOn)
{
    // Get the client rectangle of the window on which we want to center
    // Make sure the pointer is not NULL first

    if (pWndToCenterOn == NULL)
        return;
 
    CRect rectToCenterOn;
    pWndToCenterOn->GetWindowRect(&rectToCenterOn);

    // Get this window's area
    CRect rectSubDialog;
    GetWindowRect(&rectSubDialog);

    // Now rectWndToCenterOn contains the screen rectangle of the window 
    // pointed to by pWndToCenterOn.  Next, we apply the same centering 
    // algorithm as does CenterWindow()

    // find the upper left of where we should center to

    int xLeft = (rectToCenterOn.left + rectToCenterOn.right) / 2 - 
        rectSubDialog.Width() / 2;
    int yTop = (rectToCenterOn.top + rectToCenterOn.bottom) / 2 - 
        rectSubDialog.Height() / 2;

    // Move the window to the correct coordinates with SetWindowPos()
    SetWindowPos(NULL, xLeft, yTop, -1, -1,
        SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}

Listing 2。我们的brute-force CenterWindowOnOwner()函数。 然后我向CSubDialog::OnInitDialog()添加了代码,以使其处于中心位置 到主对话框,这是应用程序的主窗口: 隐藏,复制Code

BOOL CSubDialog::OnInitDialog()
{
    CDialog::OnInitDialog();

    ...

    CWnd* pMainWnd = AfxGetMainWnd();
    CenterWindowOnOwner(pMainWnd);

    return TRUE;
}

Listing 3。如何调用CenterWindowOnOwner()。 瞧!子对话框将始终以主对话框(或主对话框)为中心 应用程序窗口),无论该窗口位于屏幕的哪个位置。 本文转载于:http://www.diyabc.com/frontweb/news6786.html

posted @ 2020-08-10 02:05  Dincat  阅读(242)  评论(0编辑  收藏  举报