Talk about MFC change control size and position

  • 2020-04-02 03:04:50
  • OfStack

Use the CWnd class function MoveWindow() or SetWindowPos() to change the size and position of the control.

Void MoveWindow(int x,int y,int nWidth,int nHeight);
Void MoveWindow (LPCRECT lpRect);

The first usage needs to give the control new coordinates and width, height;
The second use gives the location of the CRect object.

Ex. :

CWnd *pWnd;
pWnd = GetDlgItem( IDC_EDIT1 ); //Gets the control pointer, IDC_EDIT1 is the control ID number
pWnd->MoveWindow( CRect(0,0,100,100) ); //Displays an edit control 100 by 100 in the upper left corner of the window

The SetWindowPos() function is more flexible and is used to modify only the position of the control and keep the size unchanged or to modify only the size and keep the position unchanged:

BOOL SetWindowPos(const CWnd* pWndInsertAfter,int x,int y,int cx,int cy,UINT nFlags);

I won't use the first parameter, which is usually set to NULL;

X, y control position; Width and height of cx and cy controls;

NFlags commonly used value:
SWP_NOZORDER: ignores the first parameter;
SWP_NOMOVE: ignore x, y, keep the position unchanged;
SWP_NOSIZE: ignore cx and cy and keep the size unchanged;
Ex. :

CWnd *pWnd;
pWnd = GetDlgItem( IDC_BUTTON1 ); //Gets the control pointer, IDC_BUTTON1 is the control ID number
pWnd->SetWindowPos( NULL,50,80,0,0,SWP_NOZORDER | SWP_NOSIZE ); //Move the button to the window at (50,80)
pWnd = GetDlgItem( IDC_EDIT1 );
pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER | SWP_NOMOVE ); //Set the size of the edit control to (100,80) in the same position
pWnd = GetDlgItem( IDC_EDIT1 );
pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER ); //The size and position of the edit control change

The above method also applies to various Windows.

The above is all the content of this article, I hope you can enjoy it.

Related articles: