专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Delphi教程 » 切换用户界面:利用INI文件实现界面无闪烁多语言切换 »正文

切换用户界面:利用INI文件实现界面无闪烁多语言切换

来源: 发布时间:星期五, 2008年12月26日 浏览:54次 评论:0
运行时我们查找当前目录下所有语言配置文件(*.ini)为了达到这个目我编写了如下搜索目录下所有语言配置文件文件名然后将文件名去掉ini扩展名保存返回:
function TForm1.SearchLanguagePack:TStrings;
var
ResultStrings:TStrings;
DosError:eger;
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;

重点在如何切换语言在ComboBox1OnChange事件中进行切换操作
这里我写了SetActiveLanguage过程用于实现这操作
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
SetActiveLanguage(ComboBox1.Text);
end;
其中SetActiveLanguage代码如下:
procedure TForm1.SetActiveLanguage(LanguageName:);
const
Translations='Translations';
Messages='Messages';
var
frmComponent:TComponent;
i:Integer;
begin
with TInile.Create(ExtractFilePath(ParamStr(0))+LanguageName+'.ini') do
begin
for i:=0 to ComponentCount-1 do { 遍历Form组件 }
begin
frmComponent:=Components[i];
frmComponent is TLabel then { 如果组件为TLabel型则当作TLabel处理以下同 }
begin
(frmComponent as TLabel).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TLabel).Caption);
end;
frmComponent is TCheckBox then
begin
(frmComponent as TCheckBox).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TCheckBox).Caption);
end;
frmComponent is TButton then
begin
(frmComponent as TButton).Caption:=
ReadString(Translations,frmComponent.Name
+'.Caption',(frmComponent as TButton).Caption);
(frmComponent as TButton).H:=
ReadString(Translations,frmComponent.Name
+'.H',(frmComponent as TButton).H);
end;
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为串变量这样提示消息也能切换比如在Button1Click事件中
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(M1);
end;
就可以根据区别语言给出区别提示文字

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

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: