I want to store user preferences (colors,toolbars on/off, panel widths in pixels) and application settings (last 10 files, default save directory, default open directory) within my Delphi Win32 application. What is the best practice for doing this?
You have two main options:
HKEY_CURRENT_USER
which is also part of the profile.Personally I prefer to use the registry since it provides hierarchical storage for free. If you use a file, then you have to do that yourself which can be a bind for more complex data.
On the other hand, if you want to write a portable app, i.e. one that can live on a memory stick, then a user settings file that sits alongside the executable is the way to go.
As @David points out, you can use the registry, files, or -- naturally -- a combination of those.
If you go for files, you have to store them in the current user's part of the file system. Indeed, it is a fundamental principle that one user should not affect any other user of the system, and Windows enforces this (for instance, you cannot save files in the Program Files directory when running without elevated privileges1).
For instance, my AlgoSim software could store its settings in the
C:\Users\Andreas Rejbrand\AppData\Roaming\Rejbrand\AlgoSim\2.0
folder. This is a typical example. You get the first part of the directory, that is,
C:\Users\Andreas Rejbrand\AppData\Roaming
by asking the operating system for the per-user app data folder. You can use the SHGetKnownFolderPath
function to find this. Use the FOLDERID_RoamingAppData
folder ID. If you need to support older versions of Windows, you can use SHGetFolderPath
instead, and use the CSIDL_APPDATA
constant.
The rest of the path normally follows the pattern
Manufacturer Name\Product Name\Product Version
What files to store? Well, the simplest way is to use old-fashioned INI files, but you can also use XML, plain-text files in your own format, or even binary files of your own design.
The second approach is to use the registry instead of files. This you probably already know how to do. If not, you'll learn that from examples easily. For instance, I could store my per-user settings in
HKEY_CURRENT_USER\Software\Rejbrand\AlgoSim\2.0
1 In this case, the operating system is smart enough to 'emulate' a per-user 'Program Files' folder. While the program thinks that it is reading from and writing to the Program Files folder, it is in fact reading from and writing to a folder in the current user's part of the file system. This way, old and badly behaved applications continue to work even in newer versions of the Microsoft Windows operating system, and, in addition, they begin to support per-user settings, which they should have done in the first place. I really think this is a major +1 to Microsoft, as I might have said before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With