設計思路
利用每個控件自帶的 Caption(顯示文字)與 Hint(提示文字)兩個字串屬性,分別儲存中英文文案;切換時互換兩屬性值,無需外部資源檔、DLL 或資料庫。
介面佈局範例
| 控件 | Caption(預設中文) | Hint(英文) | Tag |
| Button1 | 中文 | Chinese | 1 |
| Button2 | 英文 | English | 2 |
| Button3 | 忽略 | Ignore | 0 |
| CheckBox1 | 一般 | General | - |
| CheckBox2 | 高級 | Advanced | - |
| GroupBox1 | 信息 | Information | - |
| MenuItem N1 | 當前日期 | Current Date | - |
| MenuItem N2 | 幫助 | Help | - |
核心切換程式碼
procedure TForm1.FormCreate(Sender: TObject);
begin
Button1.Enabled := False; // 預設顯示中文,中文按鈕失效
Button2.Enabled := True;
end;
procedure TForm1.ChangeState(Mode: Byte); // 1=中文, 2=英文
begin
if Mode = 1 then
begin
Button1.Enabled := False; Button2.Enabled := True;
end
else
begin
Button1.Enabled := True; Button2.Enabled := False;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
Tmp: string;
begin
ChangeState(TButton(Sender).Tag); // 依 Tag 切換按鈕狀態
for i := 0 to ComponentCount - 1 do
begin
// 選單項
if Components[i] is TMenuItem then
with TMenuItem(Components[i]) do
begin
Tmp := Hint; Hint := Caption; Caption := Tmp;
end;
// 按鈕
if Components[i] is TButton then
with TButton(Components[i]) do
begin
Tmp := Hint; Hint := Caption; Caption := Tmp;
end;
// 複選框
if Components[i] is TCheckBox then
with TCheckBox(Components[i]) do
begin
Tmp := Hint; Hint := Caption; Caption := Tmp;
end;
// 群組框
if Components[i] is TGroupBox then
with TGroupBox(Components[i]) do
begin
Tmp := Hint; Hint := Caption; Caption := Tmp;
end;
end;
end;
優缺點分析
| 優點 | 缺點 |
| 零外部相依,編譯後單一 EXE 即可運行 | 僅支援雙語,擴充多語言需改用資源 DLL 或資料庫 |
| 切換即時,無需重新載入表單 | Hint 原本用途(提示文字)被佔用,需另覓方式顯示 ToolTip |
| 程式碼簡潔,利用 RTTI 遍歷元件自動處理 | 動態建立的控件需手動補充 Hint/Caption |
擴充建議
- 建立
TLanguageManager 類別統一管理語言包,支援 JSON/XML 載入。
- 利用
TypInfo RTTI 自動枚舉所有已發表屬性(Caption, Hint, Text 等)進行批次互換。
- 結合
TApplication.OnMessage 攔截 CM_HINTSHOW 自訂 ToolTip 顯示邏輯。