首页 | 社区 | 博客 | 招聘 | 文章 | 新闻 | 下载 | 读书 | 代码
亲,您未登录哦! 登录 | 注册

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

打印文章

分享到:
程序运行时,我们查找当前目录下所有的语言配置文件(*.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;
就可以根据不同的语言给出不同的提示文字。

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

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( Pfan.cn )

编程爱好者论坛

本栏最新文章