Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Mar 25, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Can I programmatically move a control in a window in Visual C++?

I'm beginning the design of an application where it would be advantageous to be able to programmatically move the position of a control on its form. Is it possible to do this using Visual C++?

Yes, all control classes (ie CEdit, CListBox, CStatic, etc) in Visual C++ are derived from CWnd, the base class containing all the fundamental functionality of a Window. Please keep in mind that neither CWnd nor any of its decendents are Window Controls but are merely C++ classes that strongly wrap Window API functions that permit communication with Window Controls such as sending a message to control to reposition itself. Hence having said that, to reposition a control on a window using Visual C++ with MFC, you could call either CWnd:: MoveWindow or CWnd:: SetWindowPos depending your needs. MoveWindow allows you to change the position and dimensions of a specified Window Control, and SetWindowPos allows you to change the position, dimensions and Z-order of a child, popup and top level windows. Z-order is the order of window on a stack of windows that reside on the Z axis which is an imaginary line that sticks straight out from the screen. For example if you want to move a button control on a CFormView derived class 26 screen units (pixels) down the Y axis from its current position you could do the following: 1. void CMyFormView::OnInitialUpdate() 2. { 3. CFormView::OnInitialUpdate(); 4. 5. // Retrieve a pointer to the button control. 6. CButton* pBtn = (CButton*)GetDlgItem(IDC_BUTTON1); 7. ASSERT(pBtn); 8. // Structure used to store the button control's dimensions. 9. RECT rect; 10. // Get button control's dimensions with respect to the screen. 11. pBtn->GetWindowRect(&rect); 12. // Convert the button control's dimensions with respect to its parent window. 13. ScreenToClient(&rect); 14. // Adjust button control's dimensions +26 pixels down the Y axis. 15. rect.top +=26; 16. rect.bottom +=26; 17. 18. // Move the button control 26 pixels down the Y axis. 19. pBtn->MoveWindow(&rect); 20. }

DevX Pro
Thanks for your registration, follow us on our social networks to keep up-to-date