C++Builder/Delphi 的拖放式設計讓介面構建極快,但控制項位置在設計時即固定。當表單尺寸改變(最大化、拖曳邊框)或使用者螢幕解析度不同,固定座標的控制項會導致介面錯亂、重疊或留白過大。本文提供三層次解決方案:OnResize 動態計算、容器控制項分組管理、系統解析度檢測與全域縮放。
TForm.OnResize 在表單建立、最大化/還原、使用者拖曳調整大小時均會觸發,是動態佈局的最佳切入點。
void __fastcall TForm1::FormResize(TObject *Sender)
{
int midX = Width / 2; // 表單客戶區寬度中點
Label1->Left = midX - Label1->Width / 2;
Button1->Left = midX - Button1->Width / 2;
}
利用 Controls[] 陣列與 ControlCount 遍歷:
void __fastcall TForm1::FormResize(TObject *Sender)
{
int midX = Width / 2;
for (int i = 0; i < ControlCount; ++i) {
TControl *ctrl = Controls[i];
ctrl->Left = midX - ctrl->Width / 2; // 全部水平置中
}
}
缺點:無法針對不同控制項套用差異化規則(如靠左、靠右、比例縮放)。
TPanel、TGroupBox、TScrollBox 等容器控制項同樣擁有 Controls[] 陣列。將相關控制項放入容器,再對容器本體定位,即可實現「群組整體移動、內部相對固定」。
void __fastcall TForm1::FormResize(TObject *Sender)
{
int midX = Width / 2;
for (int i = 0; i < ControlCount; ++i) {
TControl *ctrl = Controls[i];
ctrl->Left = midX - ctrl->Width / 2; // 表單直屬控制項置中
if (ctrl == GroupBox1) { // 針對特定容器處理內部佈局
int subMidX = GroupBox1->Width / 2;
for (int j = 0; j < GroupBox1->ControlCount; ++j) {
TControl *subCtrl = GroupBox1->Controls[j];
subCtrl->Left = subMidX - subCtrl->Width / 2; // 子控制項在 GroupBox 內置中
}
}
}
}
擴展:可為每個容器撰寫獨立的 OnResize 處理函數,封裝佈局邏輯,主表單僅負責定位容器本體。
// 專案檔 (Project1.cpp) 或表單 OnCreate 中
HDC hdc = GetDC(NULL);
int screenW = GetDeviceCaps(hdc, HORZRES);
int screenH = GetDeviceCaps(hdc, VERTRES);
ReleaseDC(NULL, hdc);
// 將 screenW/screenH 存為全域變數,供佈局計算參考
現代高解析度螢幕 (4K, Retina) 系統會縮放 (125%, 150%...)。C++Builder 10.3+ 支援 Per Monitor V2 DPI 感知,需在專案資訊清單 (.manifest) 或程式碼中宣告:
// 專案來源 .dpr 最開頭
#pragma explicit_rtti methods(__published, public) properties(__published, public) fields(__published, public, protected, private)
// 或使用 Vcl.Forms.Application.Scaled := True; (舊版)
並確保圖示、圖片資源提供多解析度版本 (1x, 2x, 3x)。
而非硬編碼像素,改用比例座標:
ctrl->Left = MulDiv(Width, ctrl->Tag, 10000); // Tag 儲存萬分比位置 (0~10000)
ctrl->Top = MulDiv(Height, ctrl->Tag >> 16, 10000); // 高 16 位存 Top 比例
設計時期即設定 Tag,執行期自動適配任意尺寸。
將上述邏輯封裝為可重用類別:
class TLayoutManager {
struct Item { TControl* Ctrl; int LeftPct, TopPct, WidthPct, HeightPct; };
std::vector- items;
public:
void Register(TControl* c, int l, int t, int w, int h) { items.push_back({c,l,t,w,h}); }
void Apply(int formW, int formH) {
for (auto &it : items) {
it.Ctrl->SetBounds(
MulDiv(formW, it.LeftPct, 10000),
MulDiv(formH, it.TopPct, 10000),
MulDiv(formW, it.WidthPct, 10000),
MulDiv(formH, it.HeightPct, 10000)
);
}
}
};
表單 OnResize 僅需呼叫 LayoutMgr.Apply(ClientWidth, ClientHeight)。
從簡單的 OnResize 置中,到容器分組、解析度檢測、比例佈局封裝,C++Builder/Delphi 完全能構建專業級自適應介面。關鍵在於:設計時期規劃佈局規則、執行期動態計算座標、封裝通用邏輯避免重複代碼。