本文摘自网上,版本归原作者所有,转载请注明!!!
以前做过一个vb的小项目,客户需要软件同时能够支持中文和英文,为此写了一个自动语言切换的模块来用,不敢独享,拿来给大家参考一下
模块 MdlLanMgr.bas : Attribute VB_Name = "ModuleLanMgr" Option Explicit
Private Declare Function GetPrivateProfileString& Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String)
Private LanguageFileName As String
'选择语言
Public Sub SelectLanguage(LanName As String) On Error Resume Next Select Case LanName '根据用户选择的语言的名称,分别读取不同的语言文件 Case "English": LanguageFileName = AddSplash(App.Path) & "English.Lan" Case "Chinese(Simplify)": LanguageFileName = AddSplash(App.Path) & "ChineseS.Lan" Case "Chinese(Traditional)": LanguageFileName = AddSplash(App.Path) & "ChineseT.Lan" Case Else: LanguageFileName = "" End Select End Sub
'翻译文字
Public Function TranslateStr(sSection As String, sKey As String, sDefVal As String) As String Dim sValue As String * 128 Dim N As Long On Error Resume Next TranslateStr = sDefVal If Not FileExists(LanguageFileName) Then Exit Function End If N = GetPrivateProfileString(sSection, sKey, sDefVal, sValue, 127, LanguageFileName) If N > 0 Then TranslateStr = Left(sValue, N) End If End Function
'自动转换Form上的一些基本控件(也可自行扩展,目前支持CommandButton,Label,OptionButton,CheckButton)
Public Sub TranslateForm(Frm As Form) Dim I As Long On Error Resume Next Frm.Caption = TranslateStr(Frm.Name, "Caption", Frm.Caption) For I = 0 To Frm.Controls.Count - 1 If (TypeOf Frm.Controls(I) Is CommandButton) Or (TypeOf Frm.Controls(I) Is Label) _ Or (TypeOf Frm.Controls(I) Is OptionButton) Or (TypeOf Frm.Controls(I) Is CheckBox) Then Frm.Controls(I).Caption = TranslateStr(Frm.Name, Frm.Controls(I).Name, Frm.Controls(I).Caption) End If Next I End Sub
调用很简单,在作为程序主窗口的Form中这么写:
Private Sub Form_Load() On Error GoTo ErrFun Language = "English" If FileExists(AddSplash(App.Path) & "Sys.Ini") Then '从程序的配置文件中读取上次设置的语言文件名称 Open AddSplash(App.Path) & "Sys.Ini" For Input As #1 Input #1, Language Close #1 End If SelectLanguage (Language) '设置全局变量,指定使用的语言 TranslateForm Me '自动转换界面文字 ErrFun: Resume Next End Sub
其它Form中都用类似的写法,在FormLoad中调用TranslateForm(Me)的方法将Form上的Button,Label等切换语言文字。
最后,用到的语言文件的格式像这样:
[FormMain] Caption=PCTV Player LabelCmd1=Start Play LabelCmd2=Edit Play List LabelCmd3=Options... LabelCmd4=Help LabelCmd5=Exit LabelCmd6=Exit && Shut down computer
[FormEdit] Caption=Edit PlayList... Cmd1=Add Program Cmd2=Edit Program Cmd3=Del Program Cmd4=Move Up Cmd5=Move Down Cmd6=Quit Edit ListView.Title1=ID ListView.Title2=Time ListView.Title3=Type ListView.Title4=Title
由于VB语言(这里指VB6.0及以前版本,VB.NET属于另一种概念了)还是挺弱的,所以也只能将就这做到这个程度了,如果要增加一些其它控件或者其它属性的自动文字转换支持,那么你必须自行扩展TranslateForm()函数。(不像Delphi,可以使用RTTI来搞定一切)
另外,比较麻烦的是如果在同时有几个Form显示着的情况下要切换界面语言,那么需要手工分别对各个窗口调用TranslateForm()函数,如果你想改进,那么可以再写个过程遍历所有窗口并调用该函数,这个就留给你来做吧。
希望这些对大家有帮助。 |
评论