頻繁呼叫 GetClientRect/GetWindowRect 時,每次都需宣告臨時 CRect 變數,程式碼冗長:
CRect rc;
::GetClientRect(hWnd, &rc);
利用繼承 CRect (或 tagRECT),建構子自動填充:
// 基於 CRect (MFC/ATL 共用)
class CClientRect : public CRect {
public:
explicit CClientRect(HWND hWnd) {
ATLASSERT(::IsWindow(hWnd));
::GetClientRect(hWnd, this);
}
};
// 不依賴 MFC/ATL,直接繼承 tagRECT
class CClientRect : public tagRECT {
public:
explicit CClientRect(HWND hWnd) {
ATLASSERT(::IsWindow(hWnd));
::GetClientRect(hWnd, this);
}
};
void OnSize(UINT, CSize sz) {
CClientRect rc(m_hWnd); // 自動取得客戶區矩形
MoveChildWindow(rc); // 直接當 CRect/RECT 用
InvalidateRect(&rc); // 隱性轉型
}
GetWindowRectclass CWindowRect : public CRect {
public:
explicit CWindowRect(HWND hWnd) {
ATLASSERT(::IsWindow(hWnd));
::GetWindowRect(hWnd, this);
}
};
CRect/tagRECT,可直接傳遞給接受 RECT* 或 CRect& 的 API。HWND。CRect 享受完整方法 (Width(), Height(), CenterPoint()…)。tagRECT 零依賴。