MFC Dialog: How to set the initial position of a modal dialog?
Q: How to set the initial position of a modal dialog?
A: There are at least two possible answers to this question. Both answers I will provide here handles the WM_INITDIALOG message.
First add a handler for the WM_INITDIALOG message to your dialog box class (this can for instance be done by using the ClassWizzard if you use a a version of VC++ prior to VC++ 2002). The message handling function for a WM_INITDIALOG message is the OnInitDialog function.
The following implementation positions the dialog at the screen coordinates x,y inside the dialog class itself:
Another possibility is to set the position when you create the dialog. To achieve this you have to add a public CPoint member variable to your dialog. This variable will hold the dialog's initial position.
// Calculate your x and y coordinates of the upper-left corner
// of the dialog (in screen coordinates) based on some logic
SetWindowPos(NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
Then you use almost the same implementation of the OnInitDialog as above. The only difference is that you use the x and y coordinates from m_point.
class CYourDialog : public CDialog
Now, when you create the dialog you set the m_point member to what suits you:
SetWindowPos(NULL, m_point.x, m_point.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
//Calculate x and y (screen coordinates)
int x = ...;
int y = ...;
dlg.m_point = CPoint( x , y );
if(dlg:DoModal() == IDOK)