; Chinese GB.ini
[Translations]
Label1.Caption = 文字1
Label2.Caption = 文字2
Label3.Caption = 語言
Button1.Caption = 按鈕1
Button2.Caption = 按鈕2
Button1.Hint = 按鈕1_提示
Button2.Hint = 按鈕2_提示
CheckBox1.Caption = 複選框1
CheckBox2.Caption = 複選框2
File1.Caption = 檔案
Exit1.Caption = 退出
[Messages]
M1 = 訊息框測試
[Translations]:元件屬性對照 (元件名.屬性名 = 翻譯文字)[Messages]:程式碼中使用的字串變數English.ini 同結構,僅翻譯「=」右側
function TForm1.SearchLanguagePack: TStrings;
var
SR: TSearchRec;
Err: Integer;
begin
Result := TStringList.Create;
Err := FindFirst(ExtractFilePath(ParamStr(0)) + '*.ini', faAnyFile, SR);
while Err = 0 do begin
Result.Add(ChangeFileExt(SR.Name, '')); // 移除 .ini 副檔名
Err := FindNext(SR);
end;
FindClose(SR);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ComboBox1.Items.AddStrings(SearchLanguagePack);
// 可設定預設語言:ComboBox1.ItemIndex := 0;
end;
procedure TForm1.SetActiveLanguage(LanguageName: string);
const
SecTrans = 'Translations';
SecMsg = 'Messages';
var
Ini: TIniFile;
Comp: TComponent;
I: Integer;
begin
Ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + LanguageName + '.ini');
try
// 遍歷所有元件
for I := 0 to ComponentCount - 1 do begin
Comp := Components[I];
// 依類型處理對應屬性
if Comp is TLabel then
TLabel(Comp).Caption := Ini.ReadString(SecTrans, Comp.Name + '.Caption', TLabel(Comp).Caption);
else if Comp is TCheckBox then
TCheckBox(Comp).Caption := Ini.ReadString(SecTrans, Comp.Name + '.Caption', TCheckBox(Comp).Caption);
else if Comp is TButton then begin
TButton(Comp).Caption := Ini.ReadString(SecTrans, Comp.Name + '.Caption', TButton(Comp).Caption);
TButton(Comp).Hint := Ini.ReadString(SecTrans, Comp.Name + '.Hint', TButton(Comp).Hint);
end
else if Comp is TMenuItem then
TMenuItem(Comp).Caption := Ini.ReadString(SecTrans, Comp.Name + '.Caption', TMenuItem(Comp).Caption);
// 可擴充支援更多控件類型...
end;
// 讀取訊息字串
M1 := Ini.ReadString(SecMsg, 'M1', M1);
finally
Ini.Free;
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
SetActiveLanguage(ComboBox1.Text);
end;
var M1: string; // 全域或表單欄位
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(M1); // 依當前語言顯示不同文字
end;
TypInfo 動態獲取屬性,不寫死類型判斷Font.Name、Color、Picture 路徑等BiDiMode 處理阿拉伯文/希伯來文INI + 元件遍歷模式,以「約定優於配置」 (元件名.屬性名 對應 INI Key) 實現極簡多語言切換。無閃爍、即時生效、零第三方依賴,極適合中小型專案快速加入多國語言支援。