Monday 20 May 2013

How to store application settings in an INI file

Usually when you write a piece of software you want to store off user information about the software, for example window positions and sizes, there are multiple ways of doing this, here is a simple example using an INI file.

uses iniFiles;

procedure TForm.SaveSettings;
var
    iniFile: TIniFile;
begin
    iniFile := TIniFile.Create(GetCurrentDir + '/Settings.ini');
    try
        iniFile.WriteInteger('MAINFORM', 'LEFT', Left);
        iniFile.WriteInteger('MAINFORM', 'TOP', Top);
        iniFile.WriteInteger('MAINFORM', 'WIDTH', Width);
        iniFile.WriteInteger('MAINFORM', 'HEIGHT', Height);
    finally
        iniFile.Free;
    end;
end;

procedure TForm.LoadSettings;
var
    iniFile: TIniFile;
begin
    iniFile := TIniFile.Create(GetCurrentDir + '/Settings.ini');
    try
        Left   := iniFile.ReadInteger('MAINFORM', 'LEFT', Left);
        Top    := iniFile.ReadInteger('MAINFORM', 'TOP', Top);
        Width  := iniFile.ReadInteger('MAINFORM', 'Width', Width);
        Height := iniFile.ReadInteger('MAINFORM', 'Height', Height);
    finally
        iniFile.Free;
    end;
end;

There are 2 procedures here that load and save the forms size and position. The values are stored in the INI file located in the same directory as the executable. Other ways of storing these values would be in the registry or in rare cases you may want to store these sort of settings in a database.

No comments:

Post a Comment