更好的 CenterWindow() 函数






4.57/5 (4投票s)
2000年8月8日

110243

778
这是一个比 CWnd::CenterWindow() 更好的、可用的替代方案。
图1。主 CenterSample
示例程序屏幕。
引言
在屏幕上居中窗口是您通常可以使用 MFC 中的 CWnd::CenterWindow()
函数完成的事情。CenterWindow()
接受一个指向 CWnd
的指针作为其参数,并且理论上该函数会将调用它的窗口相对于您传递指针的窗口居中。
pDlg->CenterWindow(AfxGetMainWnd()); // Centers pDlg against the main window?
列表 1。演示使用 CWnd::CenterWindow()
居中对话框。然而,最近在 MFC 邮件列表 上提出的一个问题是:“我有一个基于对话框的程序,用户可以单击按钮并弹出一个子对话框。如果在子对话框的 OnInitDialog()
处理程序中调用 CWnd::CenterWindow()
,对话框将始终居中在屏幕中心,而不是相对于主对话框居中。我该如何做到这一点?”
因此,我提出一个“蛮力”居中函数,它实际上比 CWnd::CenterWindow()
更好。它被称为 CSubDialog::CenterWindowOnOwner()
,我将其添加到我的示例程序的子对话框类 CSubDialog
中。
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); }列表 2。我们的蛮力
CenterWindowOnOwner()
函数。然后,我添加了代码到 CSubDialog::OnInitDialog()
中,以使其相对于主对话框居中,即应用程序的主窗口。
BOOL CSubDialog::OnInitDialog()
{
CDialog::OnInitDialog();
...
CWnd* pMainWnd = AfxGetMainWnd();
CenterWindowOnOwner(pMainWnd);
return TRUE;
}
列表 3。如何调用 CenterWindowOnOwner()
。而且瞧!子对话框将始终相对于主对话框(或主应用程序窗口)居中,无论该窗口放置在屏幕上的何处。