With this class you can Save your programs settings to a file, and load it on startup. It uses a PropertyBag for its saving and loading because if its .Contents property. This class was inspired by CVMichael.
Add a new class module to your project, name it CSettings and add the following code to itExample usage:VB Code:
Option Explicit ' CSettings 1/27/2006 Private Keys() As String Private Vals() As String Private Settings As Integer Private Sub Class_Initialize() Settings = -1 End Sub Private Function IsSet(ByVal Key As String) As Integer Dim i As Integer If Settings <> -1 Then For i = 0 To Settings If Keys(i) = Key Then IsSet = i Exit Function End If Next End If IsSet = -1 End Function Public Sub Save(ByVal Key As String, ByVal Val As String) Dim i As Integer i = IsSet(Key) If i = -1 Then Settings = Settings + 1 ReDim Preserve Keys(Settings) ReDim Preserve Vals(Settings) Keys(Settings) = Key Vals(Settings) = Val Else Vals(i) = Val End If End Sub Public Function Load(ByVal Key As String) As String Dim i As Integer i = IsSet(Key) If i = -1 Then Load = "" Else Load = Vals(i) End If End Function Public Sub SaveToFile(ByVal Filename As String) Dim PB As New PropertyBag Dim i As Integer Dim Binary() As Byte If Len(Dir(Filename)) <> 0 Then DeleteFile Filename End If PB.WriteProperty "s", Settings For i = 0 To Settings PB.WriteProperty "k" & i, Keys(i) PB.WriteProperty "v" & i, Vals(i) Next i = FreeFile Open Filename For Binary As i Binary = PB.Contents Put i, , Binary Erase Binary Close i End Sub Public Sub LoadFromFile(ByVal Filename As String) Dim PB As New PropertyBag Dim i As Integer Dim Binary() As Byte i = FreeFile Open Filename For Binary As i ReDim Binary(LOF(i)) Get i, , Binary PB.Contents = Binary Erase Binary Close i Erase Keys Erase Vals Settings = Int(PB.ReadProperty("s")) For i = 0 To Settings ReDim Preserve Keys(i) ReDim Preserve Vals(i) Keys(i) = PB.ReadProperty("k" & i) Vals(i) = PB.ReadProperty("v" & i) Next End SubVB Code:
Dim Settings As New CSettings Sub Form_Load() If Len(Dir(App.Path & "\Settings.bin")) <> 0 Then Settings.LoadFromFile App.Path & "\Settings.bin" Else Settings.Save "Started", 0 End If Settings.Save "Started", Settings.Load("Started") + 1 End Sub Sub Form_Unload() Settings.SaveToFile App.Path & "\Settings.bin" End Sub




Reply With Quote