日期:2012-12-27 浏览次数:20513 次
[Section1]
KeyWord1=Valuel
KeyWord2=Value2
……
[Section2]
KeyWord1=Value1
KeyWord2=Value2
……
其中,如果等号右边无任何内容(即Value为空),那就表示Windows应用程序已为该关键词指定了缺省值,如果在整个文件中找不到某个关键词(或整个一部分),那同样表示为它们指定了缺省值。各个部分所出现的顺序是无关紧要的,在每一个部分里,各个关键词的顺序同样也无关紧要。
读写INI文件通常有两种方式:一是在Windows中用“记事本”(Notepad)对其进行编辑,比较简单,无需赘述;二是由Windows应用程序读写INI文件,通常是应用程序运行时读取INI文件中的信息,退出应用程序时保存用户对运行环境的某些修改。
关键词的值的类型多为字符串或整数型,应分两种情况读写。为了使程序具有可维护性和可移植性,最好把对INI文件的读写封装在一个模块(RWINI.BAS)中,在RWI-NI.BAS中构造GetIniS和GetIniN函数以及SetIniS和Se-tIniN过程,在这些函数和过程中需要使用WindowsAPI的“GetPrivateprofileString”、“GetPrivateProfileInt”和“WritePrivateProfileString”函数。
RWINI.BAS模块的程序代码如下:
在General-Declearation部分中声明使用到的WindowsAPI函数:
Public Declare Function GetprivateprofileString Lib“Kernel”(ByVal lpAppName As String,ByVal lpKeyName As _
String,ByVal lpDefault As String,ByVal lpRetrm-String As String,ByVal cbReturnString As Integer, _
ByVal Filename As String)As Integer
Public Declare Function GetPrivatePfileInt Lib“Kernel”(ByVal lpAppName As String,ByVal lpKeyName As String, _
ByVal lpDefault As Integer,ByVal Filename As String)As Integer
Public Declare Funciton WritePrivateprofileString Lib“Kernel”(ByVal lpApplicationName As String, _
ByVal lpKeyName As String,ByVal lpString As String,ByVal lplFileName As String)As Integer
Public Function GetIniS(ByVal SectionName As String,ByValKeyWord As String,ByVal DefString As String)As String
Dim ResultString As String*144,Temp As Integer
Dim s As String,i As Integer
Temp%=GetPrivateProfileString(SectionName,KeyWord,"",ResultString,144,AppProfileName())
’检索关键词的值
If Temp%>0 Then ’关键词的值不为空
s=""
For i=1 To 144
If Asc(Mid$(ResultString,I,1))=0 Then
ExitFor
Else
s=s & Mid$(ResultString,I,1)
End If
Next
Else
Temp%=WritePrivateProfilesString(sectionname,KeyWord,DefString,ppProfileName())
’将缺省值写入INI文件
s=DefString
End If
GetIniS=s
End Function
Public Function GetIniN(ByVal SectionName As String,ByVal KeyWord As String,ByVal DefValue As Ineger)As Integer
Dim d As Long,s As String
d=DefValue
GetIniN=GetPrivateProfileInt(SectionName,
KeyWord,DefValue,ppProfileName())
If d<>DefValue Then
s=""
d=WritePrivateProfileString(SectionName,
KeyWord,s,AppProfileName())
End If
End Function
Public Sub SetIniS(ByVal SectionName As String,BtVal KeyWord As String,ByVal ValStr As String)
Dim res%
res%=WritePrivateprofileString(SectionName,KeyWord,ValStr,AppProfileName())
End Sub
Public Sub SetIniN(ByVal SectionName As String,ByVal KeyWord As String,ByVal ValInt As Integer)
Dim res%,s$
s$=Str$(ValInt)
res%=WriteprivateProfileString(SectionName,KeyWord,s$,AppProfileName())
End Sub
SectionName为每一部分的标题,K