有界面的软件一般用什么语言 利用INI文件实现界面无闪烁多语言切换

利用INI文件实现界面无闪烁多语言切换
程序运行时 我们查找当前目录下所有的语言配置文件(* ini) 为了达到这个目的 我编写了如下的函数搜索目录下所有的语言配置文件的文件名 然后将文件名去掉ini扩展名保存返回
function TForm SearchLanguagePack:TStrings; var ResultStrings:TStrings; DosError:integer; SearchRec:TsearchRec; begin ResultStrings:=TStringList Create; DosError:=FindFirst(ExtractFilePath(ParamStr( ))+ * ini faAnyFile SearchRec); while DosError= do begin { 返回的文件名并去掉末尾的 ini字符 } ResultStrings Add(ChangeFileExt(SearchRec Name )); DosError:=FindNext(SearchRec); end; FindClose(SearchRec); Result:=ResultStrings; end;
在Form建立的事件中添加代码 将目录下所有的语言文件名加入选择列表框中
procedure TForm FormCreate(Sender: TObject); begin ComboBox Items AddStrings(SearchLanguagePack); end;程序的重点在如何切换语言 在ComboBox 的OnChange事件中进行切换操作
这里我写了SetActiveLanguage过程用于实现这一操作
procedure TForm ComboBox Change(Sender: TObject); begin SetActiveLanguage(ComboBox Text); end;
其中SetActiveLanguage代码如下
procedure TForm SetActiveLanguage(LanguageName:string); const Translations= Translations ; Messages= Messages ; var frmComponent:TComponent; i:Integer; begin with TInifile Create(ExtractFilePath(ParamStr( ))+LanguageName+ ini ) do begin for i:= to ComponentCount 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; M :=ReadString(Messages M M ); end; end;
在这个过程中 我们遍历了Form中的所有组件 根据他们的类别和组件名动态的从ini配置文件中读出应该显示的语言文字
用遍历组件的方法比一个一个写出具体的组件维护起来要方便很多 代码的适应性也更强 其中M 为一个字符串变量 这样提示消息也能切换 比如在Button 的Click事件中
procedure TForm Button Click(Sender: TObject); begin ShowMessage(M ); end; 就可以根据不同的语言给出不同的提示文字
lishixinzhi/Article/program/Delphi/201311/25068