以前做過一個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()函數,如果你想改進,那麼可以再寫個過程遍歷所有窗口並調用該函數,這個就留給你來做吧。