Article ID: 102328
Article Last Modified on 11/21/2006
/*
* Compiler options needed: (Standard Windows Requirements)
*/
void CMyDialog::CenterDialog(CWnd *MyDialogPtr)
{
CPoint Point;
CRect DialogRect;
CRect ParentRect;
int nWidth;
int nHeight;
CWnd *DesktopWindow = NULL;
CWnd *MainWindow;
// Get the size of the dialog box.
MyDialogPtr->GetWindowRect(DialogRect);
// Get the main window.
MainWindow = AfxGetApp()->m_pMainWnd;
// Determine if the main window exists. This can be useful when
// the application creates the dialog box before it creates the
// main window. If it does exist, retrieve its size to center
// the dialog box with respect to the main window.
if (MainWindow != NULL)
MainWindow->GetClientRect(ParentRect);
// If the main window does not exist, center with respect to
// the desktop window.
else
{
DesktopWindow = MyDialogPtr->GetDesktopWindow();
DesktopWindow->GetWindowRect(ParentRect);
}
// Calculate the height and width for MoveWindow().
nWidth = DialogRect.Width();
nHeight = DialogRect.Height();
// Find the center point and convert to screen coordinates.
Point.x = ParentRect.Width() / 2;
Point.y = ParentRect.Height() / 2;
if (MainWindow)
MainWindow->ClientToScreen(&Point);
else
DesktopWindow->ClientToScreen(&Point);
// Calculate the new X, Y starting point.
Point.x -= nWidth / 2;
Point.y -= nHeight / 2;
// Move the window.
MyDialogPtr->MoveWindow(Point.x, Point.y, nWidth, nHeight, FALSE);
}
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
// Remove the comment from 1 or 2 below to correspond with
// the version of the Microsoft Foundation Classes library
// you are using.
// 1. Call CenterDialog() for version 1.0
// CenterDialog(this);
// 2. Call CenterWindow() for versions 2.0 and above
// CenterWindow();
return TRUE;
}
Additional query words: kbDlg
Keywords: kbhowto kbuidesign kbdlg KB102328