// determine owner window to center against
DWORD dwStyle = GetStyle();
HWND hWndCenter = pAlternateOwner->GetSafeHwnd();
if (pAlternateOwner == NULL)
{
if (dwStyle & WS_CHILD)
hWndCenter = ::GetParent(m_hWnd);
else
hWndCenter = ::GetWindow(m_hWnd, GW_OWNER);
if (hWndCenter != NULL)
{
// let parent determine alternate center window
HWND hWndTemp =
(HWND)::SendMessage(hWndCenter, WM_QUERYCENTERWND, 0, 0);
if (hWndTemp != NULL)
hWndCenter = hWndTemp;
}
}
// get coordinates of the window relative to its parent
CRect rcDlg;
GetWindowRect(&rcDlg);
CRect rcArea;
CRect rcCenter;
HWND hWndParent;
if (!(dwStyle & WS_CHILD))
{
// don't center against invisible or minimized windows
if (hWndCenter != NULL)
{
DWORD dwStyle = ::GetWindowLong(hWndCenter, GWL_STYLE);
if (!(dwStyle & WS_VISIBLE) || (dwStyle & WS_MINIMIZE))
hWndCenter = NULL;
}
MONITORINFO mi;
mi.cbSize = sizeof(mi);
// center within appropriate monitor coordinates
if (hWndCenter == NULL)
{
HWND hwDefault = AfxGetMainWnd()->GetSafeHwnd();
// find dialog's upper left based on rcCenter
int xLeft = (rcCenter.left + rcCenter.right) / 2 - rcDlg.Width() / 2;
int yTop = (rcCenter.top + rcCenter.bottom) / 2 - rcDlg.Height() / 2;
// if the dialog is outside the screen, move it inside
if (xLeft < rcArea.left)
xLeft = rcArea.left;
else if (xLeft + rcDlg.Width() > rcArea.right)
xLeft = rcArea.right - rcDlg.Width();
if (yTop < rcArea.top)
yTop = rcArea.top;
else if (yTop + rcDlg.Height() > rcArea.bottom)
yTop = rcArea.bottom - rcDlg.Height();