'读取配置文件
Public
Declare
Function
GetPrivateProfileString
Lib
"kernel32"
Alias
"GetPrivateProfileStringA"
(ByVal
lpApplicationName
As
String,
ByVal
lpKeyName
As
Any,
ByVal
lpDefault
As
String,
ByVal
lpReturnedString
As
String,
ByVal
nSize
As
Long,
ByVal
lpFileName
As
String)
As
Long
'写入配置文件
Public
Declare
Function
WritePrivateProfileString
Lib
"kernel32"
Alias
"WritePrivateProfileStringA"
(ByVal
lpApplicationName
As
String,
ByVal
lpKeyName
As
Any,
ByVal
lpString
As
Any,
ByVal
lpFileName
As
String)
As
Long
Public
Function
ReadOption(ByVal
Caption
As
String,
ByVal
Item
As
String,
ByVal
Path
As
String)
As
String
'Caption小节名称;Item项名称;Path配置文件路径
On
Error
Resume
Next
Dim
sBuffer
As
String
sBuffer
=
Space(128)
GetPrivateProfileString
Caption,
Item,
vbNullString,
sBuffer,
128,
Path
ReadOption
=
Left(sBuffer,
InStr(sBuffer,
vbNullChar)
-
1)
End
Function
'写入配置文件
Public
Function
WriteOption(ByVal
Caption
As
String,
ByVal
Item
As
String,
ByVal
Key
As
String,
ByVal
Path
As
String)
'Caption小节名称;Item项名称;Key项值;Path配置文件路径
Dim
sBuffer
As
String
sBuffer
=
Space(128)
sBuffer
=
Key
&
vbNullChar
WriteOption
=
WritePrivateProfileString(Caption,
Item,
sBuffer,
Path)
End
Function
'获得配置文件路径
Public
Function
GetOptPath()
As
String
GetOptPath
=
App.Path
&
"\config.ini"
End
Function
利用系统API函数 GetPrivateProfileString 可以方便地读取ini文件。使用方法如下
(1)MyApp.INI文件的内容为
VB程序读取这个ini文件,将窗口的标题换为Title指定的字符串
(2)新建一个VB工程
(3)Form1窗体代码
Option ExplicitPrivate Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" _
(ByVal lpApplicationName As Long, _
ByVal lpKeyName As Long, _
ByVal lpDefault As Long, _
ByVal lpReturnedString As Long, _
ByVal nSize As Long, _
ByVal lpFileName As Long) As Long
'------------
'读INI文件
'------------
Private Function GetValueFromINIFile(ByVal SectionName As String, _
ByVal KeyName As String, _
ByVal IniFileName As String) As String
Dim strBuf As String
'128个字符,初始化时用 0 填充
strBuf = String(128, 0)
GetPrivateProfileString StrPtr(SectionName), _
StrPtr(KeyName), _
StrPtr(""), _
StrPtr(strBuf), _
128, _
StrPtr(IniFileName)
'去除多余的 0
strBuf = Replace(strBuf, Chr(0), "")
GetValueFromINIFile = strBuf
End Function
Private Sub Form_Load()
Dim title As String
'读取INI文件中指定的节和节/键
'节的名称:AppName
'键名称:Title
title = GetValueFromINIFile("AppName", "Title", "c:\MyApp.INI")
Me.Caption = title
End Sub
(4)运行效果
窗口的标题被设置Ini文件指定的字符串!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)