一个更好的CenterWindow()函数

本文介绍了一种改进的MFC对话框居中方法,通过自定义的CenterWindowOnOwner()函数,使子对话框始终相对于主对话框居中显示,解决了CWnd::CenterWindow()函数在子对话框初始化时不能正确居中的问题。

下载演示项目- 42.2 kb图1。主CenterSample程序示例屏幕。

介绍

定心窗口在屏幕上是你通常可以做的
CWnd::CenterWindow()函数在MFC。CenterWindow ()
获取一个指向CWnd的指针作为参数,并且假定是函数
是否会将调用它的窗口的中心与传递它的窗口相对
一个指针:

隐藏,复制CodepDlg->CenterWindow(AfxGetMainWnd()); // Centers pDlg against the main window?
清单1。演示使用CWnd::CenterWindow()将对话框居中。

然而,一个问题向MFC邮件列表提出
最近被问到,“我有一个基于对话框的程序,用户可以点击一个按钮和
弹出子对话框。如果我调用CWnd::CenterWindow()在子对话框的
OnInitDialog()处理程序,对话框将始终居中
屏幕的,不居中于主对话框。我该怎么做呢?”

所以我想出了一个“强力”定心功能,它实际上工作得更好
比CWnd: CenterWindow()。它被称为
CenterWindowOnOwner(),我添加到我的示例程序的
CSubDialog sub-dialog的类:

隐藏,收缩,复制Codevoid 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()添加了代码,以使其处于中心位置
到主对话框,这是应用程序的主窗口:

隐藏,复制CodeBOOL CSubDialog::OnInitDialog()
{
CDialog::OnInitDialog();

...

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

return TRUE;

}Listing 3。如何调用CenterWindowOnOwner()。

瞧!子对话框将始终以主对话框(或主对话框)为中心
应用程序窗口),无论该窗口位于屏幕的哪个位置。

本文转载于:http://www.diyabc.com/frontweb/news6786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值