让你的VB程序支持多国语言的切换
2024-07-21 02:25:38
供稿:网友
以前做过一个vb的小项目,客户需要软件同时能够支持中文和英文,为此写了一个自动语言切换的模块来用,不敢独享,拿来给大家参考一下,如果你有什么改进也可以写信给我。。mailto:[email protected]
模块 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()函数,如果你想改进,那么可以再写个过程遍历所有窗口并调用该函数,这个就留给你来做吧。
希望这些对大家有帮助。。