於表單 OnResize 計算置中座標:
void __fastcall TForm1::FormResize(TObject *Sender)
{
int mid = Width / 2;
Label1->Left = mid - Label1->Width / 2;
Button1->Left = mid - Button1->Width / 2;
}
適用於所有控制項同樣邏輯 (如全置中):
void __fastcall TForm1::FormResize(TObject *Sender)
{
int mid = Width / 2;
for (int i = 0; i < ControlCount; i++) {
TControl *c = Controls[i];
c->Left = mid - c->Width / 2;
}
}
容器本身隨表單調整,內部子控制項再隨容器調整:
void __fastcall TForm1::FormResize(TObject *Sender)
{
int mid = Width / 2;
for (int i = 0; i < ControlCount; i++) {
TControl *c = Controls[i];
c->Left = mid - c->Width / 2; // 容器置中
if (c == GroupBox1) { // 針對 GroupBox 內部子控制項
int subMid = GroupBox1->Width / 2;
for (int j = 0; j < GroupBox1->ControlCount; j++) {
TControl *sub = GroupBox1->Controls[j];
sub->Left = subMid - sub->Width / 2;
}
}
}
}
HDC hdc = GetDC(NULL);
int scrW = GetDeviceCaps(hdc, HORZRES);
int scrH = GetDeviceCaps(hdc, VERTRES);
ReleaseDC(NULL, hdc);
// 依 scrW/scrH 比例縮放表單與控制項
同樣原理可用於列印 (GetDeviceCaps(hdc, PHYSICALWIDTH) 等)。