Module1.bas代码:
Option Explicit
Private strINI As String
Private 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
Private 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
Private Sub CreateIni(strDrv As String, strDir As String)
strINI = MakePath(strDrv, strDir)
End Sub
Public Sub WriteIniKey(strSection As String, strKey As String, strValue As String)
WritePrivateProfileString strSection, strKey, strValue, strINI
End Sub
Public Function GetIniKey(strSection As String, strKey As String) As String
Const myinifile = "/Info.ini"
strINI = myinifile
Dim strTmp As String
Dim lngRet As String
Dim i As Integer
Dim strTmp2 As String
strTmp = String$(1024, Chr(32))
lngRet = GetPrivateProfileString(strSection, strKey, "", strTmp, Len(strTmp), strINI)
strTmp = Trim(strTmp)
strTmp2 = ""
For i = 1 To Len(strTmp)
If Asc(Mid(strTmp, i, 1)) <> 0 Then
strTmp2 = strTmp2 + Mid(strTmp, i, 1)
End If
Next i
strTmp = strTmp2
GetIniKey = strTmp
End Function
Public Property Let iniFileName(ByVal New_IniPath As String)
strINI = New_IniPath
End Property
Public Property Get iniFileName() As String
iniFileName = strINI
End Property
Public Function DelIniKey(ByVal SectionName As String, ByVal KeyWord As String)
Dim RetVal As Integer
RetVal = WritePrivateProfileString(SectionName, KeyWord, 0&, strINI)
End Function
Public Function DelIniSec(ByVal SectionName As String)
Dim RetVal As Integer
RetVal = WritePrivateProfileString(SectionName, 0&, "", strINI)
End Function
Public Function AppProFileName(iniFileName)
iniFileName = "/Info"
AppProFileName = App.Path & "/" & iniFileName & ".ini"
End Function
Public Function GetIniS(ByVal SectionName As String, ByVal KeyWord 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(iniFileName))
'检索关键词的值
If Temp% > 0 Then '关键词的值不为空
s = ""
For i = 1 To 144
If Asc(Mid$(ResultString, i, 1)) = 0 Then
Exit For
Else
s = s & Mid$(ResultString, i, 1)
End If
Next
Else
Temp% = WritePrivateProfileString(SectionName, KeyWord, DefString, AppProFileName(iniFileName))
'将缺省值写入INI文件
s = DefString
End If
GetIniS = s
End Function
窗体代码:
Private Sub Command1_Click()
Read_Info
End Sub
Private Sub Read_Info()
myIni.iniFileName = App.Path & myinifile
myIni.WriteIniKey "myInfo", "Name", Text1.Text
End Sub
Private Sub Command2_Click()
Text2.Text = myIni.GetIniS("myInfo", "Name", myinifile)
End Sub
Ini文件:
[myInfo]
Name=VB读取ini文件
Age=25
Phone=1363868746*