One of my colleague asked me. “Why I can’t set the cursor position on a button during OnInitDialog? I need to set the cursor over a button inside the dialog during startup.” The snippet looks like below
BOOL CCursorPositionDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CRect rect;
GetDlgItem( IDC_BUTTON2 )->GetWindowRect( rect );
SetCursorPos(rect.left, rect.top );
}
The reason is, the Window initialization has not completed during OnInitDialog operation (even window is not displayed). Once after OnInitDialog returns, the dialog will be positioned, the input focus will be set the child control and finally the dialog is displayed. Also if you notice the, GetWindowRect returns incorrect window cordinate during OnInitDialog execution.
To solve this issue, it’s necessary to rely on other activation functions like WM_ACTIVATE or WM_WINDOWPOSCHANGED (only once) function
void CCursorPositionDlg::OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized)
{
CDialog::OnActivate(nState, pWndOther, bMinimized);
if( WA_ACTIVE == nState )
SetMousePosition();
}
Alternate method (not recommended)
void CCursorPositionDlg::OnWindowPosChanged(WINDOWPOS* lpwndpos)
{
CDialog::OnWindowPosChanged(lpwndpos);
static bool bFirst = true;
if( bFirst) { PositionButton(); bFirst = false;}
}