在我们【改变窗体的位置及大小】中有讲解类似的内容, 这一节将讲述更高级一些的API,它不仅改变窗体的位置,大小还可以改变窗体间的前后顺序即Z-ORDER, 另外支持控制窗体其他属性如:显示/隐藏, 更新后窗体刷新状态等.
(一) 函数定义及演示代码
BOOL SetWindowPos(HWND hWnd, HWND hInsertAfter, int x, int y, int cx, int cy, UINT nFlag)
hInsertAfter 参数说明:
HWND_BOTTOM 将当前窗体置于所有最顶层窗体的最低层
- HWND_NOTOPMOST 将当前窗体置于所有最顶层窗体之下 HWND_TOP 将当前窗体置于项层 HWND_TOPMOST 将当前窗体置于最顶层
设置指定窗体(控件、弹出式窗体和顶层窗体)的位置,大小和z-order
Code 1: 通过SetWindowPos 将主窗体移动到屏幕客户区中间
//--: Move Main wnd to center of screen RECT rtMainWnd ; GetClientRect ( hWnd , & rtMainWnd ); UINT nWndWidth = ( rtMainWnd . right - rtMainWnd . left ); UINT nWndHeight = ( rtMainWnd . bottom - rtMainWnd . top ); UINT nLeft = ( nSrnWidth - nWndWidth ) / 2; UINT nTop = ( nSrnHeight - nWndHeight ) / 2; SetWindowPos ( hWnd , NULL , nLeft , nTop , nWndWidth , nWndHeight , SWP_NOSIZE | SWP_NOZORDER );
Code 2: 通过SetWindowPos 改变控件大小并居中对齐(将控件放大一倍)
//--: Move "Move Center" Button to center of client area and inflate RECT rtBtnMove ; GetClientRect ( hBtnWndMove , & rtBtnMove ); UINT nMoveBtnWidth = 200; UINT nMoveBtnHeight = 100; UINT nX = ( nWndWidth - nMoveBtnWidth ) / 2; UINT nY = ( nWndHeight - nMoveBtnHeight ) / 2; SetWindowPos ( hBtnWndMove , NULL , nX , nY , nMoveBtnWidth , nMoveBtnHeight , SWP_NOZORDER );
Code 3: 通过SetWindowPos 改变主窗体的z-ORDER(动态设置到最顶层或取消最顶层属性)
static bool bTopMost = false ; HWND hWndInsertAfter ; if ( bTopMost ) { hWndInsertAfter = HWND_NOTOPMOST ; // HWND_BOTTOM; //HWND_TOP; SetWindowText ( hBtnWndState , _T ( "To TopMost" )); bTopMost = false ; } else { hWndInsertAfter = HWND_TOPMOST ; SetWindowText ( hBtnWndState , _T ( "To NoTopMost" )); bTopMost = true ; } SetWindowPos ( hWnd , hWndInsertAfter , 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );