三度网教程:是一个免费提供流行视频软件教程、在线学习分享的学习平台!

运用INI文件完成界面无闪烁多语言切换

时间:2024/6/10作者:未知来源:三度网教程人气:


程序运行时,我们查找当前目录下所有的语言配置文件(*.ini),为了达到这个目的,我编写了如下的函数搜索目录下所有的语言配置文件的文件名,然后将文件名去掉ini扩展名保存返回:
function TForm1.SearchLanguagePack:TStrings;
var
ResultStrings:TStrings;
DosError:integer;
SearchRec:TsearchRec;
begin
ResultStrings:=TStringList.Create;
DosError:=FindFirst(ExtractFilePath(ParamStr(0))+'*.ini', faAnyFile, SearchRec);
while DosError=0 do
begin
{ 返回的文件名并去掉末尾的.ini字符 }
ResultStrings.Add(ChangeFileExt(SearchRec.Name,''));
DosError:=FindNext(SearchRec);
end;
FindClose(SearchRec);
Result:=ResultStrings;
end;

在Form建立的事件中添加代码,将目录下所有的语言文件名加入选择列表框中。
procedure TForm1.FormCreate(Sender: TObject);
begin
ComboBox1.Items.AddStrings(SearchLanguagePack);
end;

程序的重点在如何切换语言,在ComboBox1的OnChange事件中进行切换操作。
这里我写了SetActiveLanguage过程用于实现这一操作。
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
SetActiveLanguage(ComboBox1.Text);
end;
其中SetActiveLanguage代码如下:
procedure TForm1.SetActiveLanguage(LanguageName:string);
const
Translations='Translations';
Messages='Messages';
var
frmComponent:TComponent;
i:Integer;
begin
with TInifile.Create(ExtractFilePath(ParamStr(0))+LanguageName+'.ini') do
begin
for i:=0 to ComponentCount-1 do { 遍历Form组件 }
begin
frmComponent:=Components[i];
if frmComponent is TLabel then { 如果组件为TLabel型则当作TLabel处理,以下同 }
begin
(frmComponent as TLabel).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TLabel).Caption);
end;
if frmComponent is TCheckBox then
begin
(frmComponent as TCheckBox).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TCheckBox).Caption);
end;
if frmComponent is TButton then
begin
(frmComponent as TButton).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TButton).Caption);
(frmComponent as TButton).Hint:=
ReadString(Translations,frmComponent.Name
+'.Hint',(frmComponent as TButton).Hint);
end;
if frmComponent is TMenuItem then
begin
(frmComponent as TMenuItem).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TMenuItem).Caption);
end;
end;
M1:=ReadString(Messages,'M1',M1);
end;
end;
在这个过程中,我们遍历了Form中的所有组件,根据他们的类别和组件名动态的从ini配置文件中读出应该显示的语言文字。


用遍历组件的方法比一个一个写出具体的组件维护起来要方便很多,代码的适应性也更强。
其中M1为一个字符串变量,这样提示消息也能切换,比如在Button1的Click事件中
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(M1);
end;
就可以根据不同的语言给出不同的提示文字。

好了,整个工程就做完了,你可以运行测试一下,是不是切换迅速而且无闪烁。

关键词:  运用INI文件完成界面无闪烁多语言切换





Copyright © 2012-2018 三度网教程(http://www.3du8.cn) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版