CRect(); CRect(int l, int t, int r, int b); CRect(const RECT& src); CRect(LPCRECT lpSrc); CRect(POINT pt, SIZE sz); CRect(POINT topLeft, POINT bottomRight);
int Width() const; int Height() const; CSize Size() const; CPoint& TopLeft(); CPoint& BottomRight(); CPoint CenterPoint() const;
rect + point → 平移rect + rect → 並集(外包矩形)rect &= rect → 交集rect |= rect → 並集PtInRect(pt) → 點包含測試CPoint(); CPoint(int x, int y); CPoint(POINT pt); CPoint(SIZE sz); CPoint(LPARAM dw); // 低字x,高字y
pt1 + pt2、pt1 - pt2、pt += sz、pt -= szCSize operator-(POINT pt) → 向量差LPCTSTR,可直接傳給 API。str.Format(_T("Val=%d"), n)。| 函數 | 說明 |
|---|---|
GetLength() | 字符數(不含結束符) |
GetAt(int idx) | 單字符讀取 |
SetAt(int idx, TCHAR ch) | 單字符修改 |
operator[] | 雙向訪問 str[i] |
Find(ch/substr) | 查找,返回索引或 -1 |
Replace(old, new) | 全局替換 |
Left(n)/Right(n)/Mid(pos, len) | 子串提取 |
MakeUpper()/MakeLower() | 大小寫轉換 |
Trim()/TrimLeft()/TrimRight() | 去除空白字符 |
Compare(str)/CompareNoCase(str) | 比較 |
operator+ | 拼接 s1 + s2 |
LoadString(ID) | 從資源加載 |
CSize(); CSize(int cx, int cy); CSize(SIZE sz); CSize(POINT pt); // cx=寬度, cy=高度, 支持 + - 與 CPoint 運算
CRect rc(10,10,100,80);
CPoint pt = rc.CenterPoint(); // (55,45)
CSize sz = rc.Size(); // (90,70)
rc.DeflateRect(5,5); // 內縮 → (15,15,95,75)
rc.OffsetRect(CSize(10,0)); // 右移 → (25,15,105,75)
CString str;
str.Format(_T("Rect: (%d,%d)-(%d,%d)"), rc.left, rc.top, rc.right, rc.bottom);
CRect/CPoint/CSize 構成 MFC 坐標幾何運算體系,CString 解決字符串內存管理痛點。熟練掌握構造、屬性獲取、運算符重載與常用成員,能大幅減少 Windows 繪圖、佈局、字符串處理的樣板代碼。本文整理自 51CTO 博客「MFC中常用類,宏,函數介紹」。