Friday, July 14, 2006

Using an INI file

Nothing complex about it.

We want to store data that reflects our run-time in a file quite separate from the program. INI files have been around for a long time. They are text files, and a reasonably competent user can edit them. A reasonably competent designer (like you!) can build a GUI form for a user interface.

Let us start by writing a small chunk of application code to demonstrate using an INI file.

References

Set a reference to the utility library UW.DOT from within your project.

Constants


In your constants module, declare two public constants:

Public Const strcDriveLetter As String = "DriveLetter"
Public Const strcDriveLetterDefault As String = "C"

Program code


In a module write a very simple test macro:

Sub test()
MsgBox UW.UT_ProfileStrings.strGPA(Publics.strcDriveLetter, Publics.strcDriveLetterDefault)
End Sub

You can, of course, omit the explicit module names:

Sub test()
MsgBox strGPA(strcDriveLetter, strcDriveLetterDefault)
End Sub

Testing the code


Run the little test macro.

You will observe a pop-up message box bearing the letter "C".
The INI file

In your Documents and settings folder locate the file Utils.INI.

Its contents should look like this:
[Utils]
DriveLetter=C

Changing the INI file

While you have the INI file open in Notepad, change the drive letter to be "D".

Re run the little test macro and observe the pop-up message box bearing the letter "D"
How it works

The procedure strGPA looks for a suitable INI file. If it doesn't find one, it builds one!

Within that file it looks for a key as stated in the first parameter of the call to strGPA; in our case the first parameter is "strcDriveLetter", so strGPA looks for a key "DriveLetter".

If the given parameter can not be found, strGPA creates a key and value using the second parameter of the call.; in our case the second parameter was "strcDriveLetterDefault" so the value defaults to "C", and that value is written to the INI file.

What is so good about all this?

I am glad you asked.

First off, you don't need to worry about the INI file. Just define your key names and default values, and strGPA does the rest.

Next, your user interface can include a ‘panic" button; resetting an INI file to default values is as simple as deleting the INI file. Your panic button merely KILLs the INI file, and each subsequent call will store and return the default values.

There's more – a strPPA function for Putting parameters to an INI file, section management, and the use of value strings much longer than the Microsoft limit of 255 characters.

As well the source code is switchable between registry, regular INI and long-value INI file methods.

More later

0 Comments:

Post a Comment

<< Home