2008年12月19日 星期五

[VB] 利用GetPrivateProfileString來讀取ini檔

1. 宣告GetPrivateProfileString

Private Declare Function GetPrivateProfileString _
Lib "kernel32" Alias "GetPrivateProfileStringA" _
(ByVal lpSectionName As String, _
ByVal lpKeyName As Any, _
ByVal lpDefault As String, _
ByVal lpbuffurnedString As String, _
ByVal nBuffSize As Long, _
ByVal lpFileName As String) As Long

2. 記得初始化回傳的buff的大小,如果沒有先初始化就傳入,會造成crash
'初始化return buffer長度, 如果沒有初始化會造成crash bug
Dim buff As String * 50
Dim Ret As Long
Dim iniFile As String
Dim key As String

'App.Path代表程式所在的路徑
iniFile = App.Path & "\my.ini"
key = "mykey"

'讀取iniFile裡面的key, buff pair
'ex :
'[My Section]
'mykey=mybuff
'讀取結果為buff = "mybuff"
Ret = GetPrivateProfileString("My Section", key, "0", buff, 50, iniFile)


參考資料 :
MSDN

沒有留言: