窗体有三个最基本的属性:位置,大小,Z-Order, Windows 对于改变窗体位置和大小这两个更常用提供了更简单的函数.
(一)改变窗体大小和位置
BOOL MoveWindow(HWND hWnd, int x, int y, int nWidth, int nHeight, BOOL bRepaint)
改变指定窗体的起始位置以及窗体大小,最后一个参数是改变是否重绘窗体
以下代码演示了将窗体置桌面客户区中间,以及将控件置于窗体客户区中间并放大一倍
UINT nSrnWidth = GetSystemMetrics(SM_CXFULLSCREEN);
UINT nSrnHeight = GetSystemMetrics(SM_CYFULLSCREEN);
RECT rtWnd;
GetWindowRect(hWnd, &rtWnd);
UINT nWndWidth = (rtWnd.right - rtWnd.left);
UINT nWndHeight = (rtWnd.bottom - rtWnd.top);
MoveWindow(hWnd, (nSrnWidth - nWndWidth) / 2, (nSrnHeight - nWndHeight) / 2, nWndWidth, nWndHeight, TRUE);
HWND hBtnMove = GetDlgItem(hWnd, wParam);
UINT nBtnWidth = 200;
UINT nBtnHeight = 100;
MoveWindow(hBtnMove, (nWndWidth - nBtnWidth) / 2, (nWndHeight - nBtnHeight) / 2, nBtnWidth, nBtnHeight, TRUE);
(二)改变窗体大小和位置触发的消息
1. WM_WINDOWPOSCHANGING
2. WM_WINDOWPOSCHANGED
3. WM_MOVE
4. WM_SIZE
5. WM_NCCALCSIZE
case WM_WINDOWPOSCHANGING:
{
TCHAR szInfo[128];
_stprintf(szInfo, _T("Step %d: WM_WINDOWPOSCHANGING\n"), ++nStep);
OutputDebugString(szInfo);
break;
}
case WM_WINDOWPOSCHANGED:
{
TCHAR szInfo[128];
_stprintf(szInfo, _T("Step %d: WM_WINDOWPOSCHANGED\n"), ++nStep);
OutputDebugString(szInfo);
break;
}
case WM_MOVE:
{
TCHAR szInfo[128];
_stprintf(szInfo, _T("Step %d: WM_MOVE\n"), ++nStep);
OutputDebugString(szInfo);
break;
}
case WM_SIZE:
{
TCHAR szInfo[128];
_stprintf(szInfo, _T("Step %d: WM_SIZE\n"), ++nStep);
OutputDebugString(szInfo);
break;
}
case WM_NCCALCSIZE:
{
TCHAR szInfo[128];
_stprintf(szInfo, _T("Step %d: WM_NCCALCSIZE\n"), ++nStep);
OutputDebugString(szInfo);
break;
}
程序启动时结果:
Step 1: WM_NCCALCSIZE
Step 2: WM_SIZE
Step 3: WM_MOVE
Step 4: WM_WINDOWPOSCHANGING
Step 5: WM_WINDOWPOSCHANGING
Step 6: WM_WINDOWPOSCHANGED
移动窗体后结果:
Step 71: WM_WINDOWPOSCHANGING
Step 72: WM_WINDOWPOSCHANGED
Step 73: WM_MOVE
Step 74: WM_WINDOWPOSCHANGING
Step 75: WM_WINDOWPOSCHANGED
Step 76: WM_MOVE
Step 77: WM_WINDOWPOSCHANGING
Step 78: WM_WINDOWPOSCHANGED
Step 79: WM_MOVE
Step 80: WM_WINDOWPOSCHANGING
Step 72: WM_WINDOWPOSCHANGED
Step 73: WM_MOVE
Step 74: WM_WINDOWPOSCHANGING
Step 75: WM_WINDOWPOSCHANGED
Step 76: WM_MOVE
Step 77: WM_WINDOWPOSCHANGING
Step 78: WM_WINDOWPOSCHANGED
Step 79: WM_MOVE
Step 80: WM_WINDOWPOSCHANGING