接前面两小节,看看ini文件的实际运用:
language_en.ini:存放英文内容。具体内容如下:
[gui]
appname=This is my App
language=Choose Language
Save=Save
Open=Open
Exit=Exit
两个ini文件相比较,节名称相同,键名称相同,键值不同。
新建工程后添加一个模块,主要放置要调用的api函数声明,由于本节教程只有一个窗体,也可以将api函数的声明放在窗体中。内容如下:
Module Module1 Public 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 Integer,ByVal lpFileName As String) As Integer Public Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" ( ByVal lpApplicationName As String,ByVal lpString As String,ByVal lpFileName As String) As Integer End Module根据选择的语言,载入相应的ini文件:
Private Sub rbChinese_CheckedChanged(sender As Object,e As EventArgs) Handles rbChinese.CheckedChanged,rbEnglish.CheckedChanged If rbChinese.Checked = True Then getGuiLanguage("d:\language_ch.ini") Else getGuiLanguage("d:\language_en.ini") End If End Sub实际载入ini内容的方法:
Private Sub getGuiLanguage(ByVal filename As String) lblAppName.Text = getKeyValue("gui","appname",filename) gbChooseLanguage.Text = getKeyValue("gui","language",filename) btnSave.Text = getKeyValue("gui","Save",filename) btnOpen.Text = getKeyValue("gui","Open",filename) btnExit.Text = getKeyValue("gui","Exit",filename) End Sub
读取ini文件键值:
Private Function getKeyValue(ByVal sectionName As String,ByVal keyName As String,ByVal filename As String) As String Dim Rvalue As Integer Dim BufferSize As Integer BufferSize = 255 Dim keyValue As String keyValue = Space(BufferSize) Rvalue = GetPrivateProfileString(sectionName,keyName,"",keyValue,BufferSize,filename) If Rvalue = 0 Then keyValue = "(没有获得相应的值)" Else keyValue = keyValue.Substring(0,Rvalue) End If Return keyValue End Function
当窗口载入时,默认载入中文:
Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load getGuiLanguage("d:\language_ch.ini") End Sub
所有的代码都写完了。
但是,以上代码实际是存在问题的。
在 getKeyValue()方法 keyValue = keyValue.Substring(0,Rvalue)一句设置断点进行调试会发现,使用substring方法返回来的数据并不正确:调用GetPrivateProfileString获得的数据:
在 getKeyValue()方法 keyValue = keyValue.Substring(0,Rvalue)一句设置断点进行调试会发现,使用substring方法返回来的数据并不正确:调用GetPrivateProfileString获得的数据:
获得数据的长度:
'===== 截断chr0 Private Function GetIniValue(ByVal msg As String) As String Dim PosChr0 As Integer PosChr0 = msg.IndexOf(Chr(0)) If PosChr0 <> -1 Then msg = msg.Substring(0,PosChr0) GetIniValue = msg End Function
keyValue = keyValue.Substring(0,Rvalue)
替换为:
替换为:
keyValue = GetIniValue(keyValue)
最后看看运行情况:
由于.net平台下C#和vb
.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录