简体   繁体   中英

Setting the Position of an MFC Dialog

I need to set the position of an MFC Dialog to some relative position (Upper Right Corner) to it's parent dialog. I am using the following code:

MainFrame.h:

/*Creation of Dialog*/
SearchCommands* searchDialog;

MainFrame.cpp:

/*In Constructor*/
searchDialog = new SearchCommands();

/*In an Init Method*/
if (!searchDialog->Create(IDD_COMMANDS_SEARCH, this))
{
    TRACE0("Failed to create Search Dialog\n");
    delete searchDialog;
}

/*Button Click Event*/
void CMainFrame::OnSearchButton()
{
    /*Get the ordinates of parent*/
    RECT rect;
    CWnd::GetWindowRect(&rect);

   /*searchDialog is the pointer to a dynamically created Dialog*/
   searchDialog->SetWindowPos(&CWnd::wndNoTopMost,rect.left,rect.bottom,rect.left,rect.bottom,SWP_SHOWWINDOW );

   searchDialog->ShowWindow(SW_SHOWNORMAL);
}

But the Dialog disappears instead of being shown properly. I could not understand how the parameters should be passed to CWnd::SetWindowPos method so may be I am doing something wrong there.

Any guidance will be appreciated.

You need to pass relative coordinates to SetWindowPos if the window is a child window. GetWindowRect returns you screen (absolute) coordinates. You cannot pass these to SetWindowPos for your scenario. Use GetClientRect on the parent and pass this rect to SetWindowPos .

RECT rect;
CWnd::GetClientRect(&rect);   // Only line changed
searchDialog->SetWindowPos(&CWnd::wndNoTopMost,rect.left,rect.bottom,rect.left,rect.bottom,SWP_SHOWWINDOW );

Try this:

CRect rect;
searchDialog->GetWindowRect(rect);
int dx = rect.Width();
int dy = rect.Height();
GetWindowRect(rect);
rect.left = rect.right - dx;
rect.bottom = rect.top + dy;
searchDialog->MoveWindow(rect);
searchDialog->ShowWindow(SW_SHOW);

This will move your dialog the upper right position of your parent window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM