設定ファイルの読み書き APIで便利な機能

設定ファイルに、アプリケーションのパラメータや、何やらかんやらを保存しておきたいけど、どうやったらいいの?

便利なAPIがあります。

'設定ファイルに書きこむAPI呼び出し
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

'設定ファイルから読みこむAPI呼び出し
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

書くのは簡単

'設定ファイルに書きこむ
Dim i%, mSection$, mEntry$, mValue$, mPath$
    mSection = "User"
    mEntry = "Name"
    mValue = "Oota"
    mPath = "C:\Apli\Prog.ini"
    i = WritePrivateProfileString(mSection, mEntry, mValue, mPath)

だけど、読むのはちょっと面倒かな?

'設定ファイルから読みこむ
Const STRINGMAX = 256
Dim i%, a$, defVal$, mSection$, mEntry$, mValue$, mPath$
    mSection = "User"
    mEntry = "Name"
    mPath = "C:\Apli\Prog.ini"
    defVal = String$(1, 0)
    a$ = String$(STRINGMAX + 2, 0)
    i = GetPrivateProfileString(mSection, mEntry, defVal, a$, STRINGMAX, mPath)
    If i <= 0 Then
        mValue = vbNullString
    Else
        i = InStr(a$, Chr$(0))
        mValue = Trim$(Left(a$, i - 1))
    End If
'これで mValue に読みこめます。

ようこそ、VBの世界へ APIで便利な機能

このホームページのホストは です。 無料ホームページをどうぞ!