The Windows Registry
Windows and many programs keep their settings in the Registry, a tree of keys that hold values. This lesson reads and writes values of every common type in HKEY_CURRENT_USER, lists values and sub-keys, and cleans up after itself. It runs on Windows only.
What you will learn#
- the Registry as a tree of keys with values,
HKEY_CURRENT_USERand why it is the safe place to write,CreateSubKey,OpenSubKey,SetValue,GetValue,- the value kinds:
String,DWord,QWord,MultiString,ExpandString,Binary, - listing values and sub-keys, deleting them,
- the rules for a program that writes to the Registry.
The tutorial Settings saved settings in a file. On Windows, programs often use the Registry for the same job, and a program that works with Windows (file types, start-up, system settings) must.
The program#
# the Windows Registry - keys and values in HKEY_CURRENT_USER, value types, listing, a settings class, and deleting what you made
# (Windows only: anywhere else the program says so and stops)
load "dotnet.ring"
using {
"System"
"Microsoft.Win32"
}
C_PATH = "Software\RingDotNetTutorial"
func main
if not iswindows()
? "The Registry exists only on Windows."
return
ok
# The Registry is a tree of KEYS (like folders) that hold VALUES (a name and data with a type). Windows and many programs keep their
# settings in it. The part HKEY_CURRENT_USER (HKCU) belongs to the user who is logged in and needs no special rights; the part
# HKEY_LOCAL_MACHINE is for all users and needs an administrator for writing. This lesson writes only in its own key under HKCU
# and deletes it at the end.
oUser = new Registry().CurrentUser
oUser.DeleteSubKeyTree([ :subkey = C_PATH, :throwOnMissingSubKey = False ]) # a key from an earlier run goes away (False: no error when it is missing)
# 1. CreateSubKey makes a key (or opens it when it exists) and gives it ready for writing
oKey = oUser.CreateSubKey(C_PATH)
? "1. the key HKEY_CURRENT_USER\" + C_PATH + " was made: " + (not oKey.isNull())
# 2. SetValue(name, data, kind). The kind says how Windows stores the data: String, DWord (a 32-bit number), QWord (64 bits),
# MultiString (a list of texts), ExpandString (a text with %NAME% variables that Windows replaces) and Binary (bytes).
oKey.SetValue([ :name = "UserName", :value = "Ann", :valueKind = "String" ])
oKey.SetValue([ :name = "WindowWidth", :value = 1280, :valueKind = "DWord" ])
oKey.SetValue([ :name = "LastFiles", :value = stringArray(["a.txt","b.txt","c.txt"]), :valueKind = "MultiString" ]) # MultiString needs a string[]: a List<string> and ToArray()
oKey.SetValue([ :name = "DataFolder", :value = "%USERPROFILE%\Data", :valueKind = "ExpandString" ])
oKey.SetValue([ :name = "BigNumber", :value = 5000000000, :valueKind = "QWord" ]) # a number above 2147483647 needs 64 bits
# Binary needs a real byte[] object. A Ring text would be written as a String, so the bytes are put into a byte buffer (dnBuffer) first:
# the buffer is a .NET object that holds a byte[], and a parameter of type object receives that array.
oKey.SetValue([ :name = "Signature", :value = dnBuffer(char(1) + char(2) + char(0) + char(254) + char(255)), :valueKind = "Binary" ])
? nl + "2. values written: " + oKey.ValueCount
# 3. Reading: GetValue(name, default) gives the data in the form that fits its kind, or the default when the name is missing
? nl + "3. UserName = " + oKey.GetValue([ :name = "UserName", :defaultValue = "(none)" ])
? " WindowWidth = " + oKey.GetValue([ :name = "WindowWidth", :defaultValue = 800 ]) + " (a number, so " + (oKey.GetValue([ :name = "WindowWidth", :defaultValue = 800 ]) + 20) + " after + 20)"
? " Missing = " + oKey.GetValue([ :name = "Missing", :defaultValue = "(default)" ])
? " LastFiles = " + listText(oKey.GetValue("LastFiles").toList())
cFolder = oKey.GetValue("DataFolder")
? " DataFolder = ends with \Data: " + (right(cFolder,5) = "\Data") + ", still has a % sign: " + (substr(cFolder,"%") > 0) + " (Windows replaced %USERPROFILE%; the path is not printed because it holds your user name)"
? " BigNumber = " + oKey.GetValue("BigNumber") + " (a 64-bit number)"
cSignature = oKey.GetValue("Signature") # a byte[] comes back as a Ring text of bytes
? " Signature = " + len(cSignature) + " bytes, in hexadecimal " + new Convert().ToHexString(cSignature) + " (Binary)"
# 4. The kind of a value, and a list of all values. GetValueKind tells how it is stored.
? nl + "4. all the values with their kinds:"
aNames = sort(oKey.GetValueNames().toList())
for cName in aNames
? " " + padRight(cName,12) + oKey.GetValueKind(cName)
next
# 5. Sub-keys: a key can hold other keys, like folders. GetSubKeyNames lists them.
oChild = oKey.CreateSubKey("Window1")
oChild.SetValue([ :name = "Left", :value = 100, :valueKind = "DWord" ])
oChild.SetValue([ :name = "Top", :value = 50, :valueKind = "DWord" ])
oChild.Close()
oKey.CreateSubKey("Window2").Close()
? nl + "5. sub-keys: " + listText(sort(oKey.GetSubKeyNames().toList()))
oRead = oKey.OpenSubKey("Window1")
? " Window1 has Left = " + oRead.GetValue("Left") + ", Top = " + oRead.GetValue("Top")
oRead.Close()
# 6. Delete one value, and the whole tree at the end. Always clean up what a test or a sample wrote.
oKey.DeleteValue("BigNumber")
? nl + "6. after DeleteValue(BigNumber): " + oKey.ValueCount + " values"
oKey.Close()
oUser.DeleteSubKeyTree(C_PATH)
? " the key was deleted: " + oUser.OpenSubKey(C_PATH).isNull()
func listText aList
cText = ""
for item in aList
if cText != ""
cText += ", "
ok
cText += "" + item
next
return cText
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))
# a string[] from a Ring list (the registry wants the exact type)
func stringArray aList
oList = new List([ :typeArguments = ["System.String"] ])
for cItem in aList
oList.Add(cItem)
next
return oList.ToArray()1. the key HKEY_CURRENT_USER\Software\RingDotNetTutorial was made: 1
2. values written: 6
3. UserName = Ann
WindowWidth = 1280 (a number, so 1300 after + 20)
Missing = (default)
LastFiles = a.txt, b.txt, c.txt
DataFolder = ends with \Data: 1, still has a % sign: 0 (Windows replaced %USERPROFILE%; the path is not printed because it holds your user name)
BigNumber = 5000000000 (a 64-bit number)
Signature = 5 bytes, in hexadecimal 010200FEFF (Binary)
4. all the values with their kinds:
BigNumber QWord
DataFolder ExpandString
LastFiles MultiString
Signature Binary
UserName String
WindowWidth DWord
5. sub-keys: Window1, Window2
Window1 has Left = 100, Top = 50
6. after DeleteValue(BigNumber): 5 values
the key was deleted: 1This program uses a few generic functions (dnNewGeneric, dnBuffer) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Keys and values#
The Registry looks like a file system: keys are the folders, and each key holds values, a name with data and a type. The big branches are hives: HKEY_CURRENT_USER (HKCU) belongs to the user who is logged in, HKEY_LOCAL_MACHINE (HKLM) is for the whole computer, HKEY_CLASSES_ROOT holds the file types. The program writes only in HKCU, under its own key Software\RingDotNetTutorial, because that needs no administrator rights and does not affect other users. HKLM needs an administrator to write.
Registry.CurrentUser is a static property of the class, read through new Registry().CurrentUser. CreateSubKey(path) makes a key (or opens it when it exists) for writing, OpenSubKey(path) opens an existing one for reading (and answers null when it does not exist), and Close() lets go of it. Paths use the backslash: in a Ring text "Software\RingDotNetTutorial" is written as it is.
The kinds of value#
SetValue([ :name = ..., :value = ..., :valueKind = ... ]) writes a value, and the kind says how Windows stores it:
| Kind | Data | Use |
|---|---|---|
String | text | names, paths |
DWord | a 32-bit whole number | sizes, flags, counters |
QWord | a 64-bit whole number | big numbers (5 000 000 000 does not fit 32 bits) |
MultiString | a list of texts | a list of recent files |
ExpandString | text with %NAME% variables | a path such as %USERPROFILE%\Data: GetValue gives the text with the variable already replaced |
Binary | bytes | pictures, encrypted data |
A MultiString needs a real string[], so the program builds one from a List<string> with ToArray() (stringArray). A Binary value needs a real byte[] object, and a Ring text would be written as a String. So the program puts the bytes into a byte buffer first: dnBuffer(bytes) makes a .NET object that holds a byte[], and a parameter of type object (the data of SetValue) receives that array. Reading a Binary value gives a byte[], which is a Ring text of bytes: Signature has the five bytes 01 02 00 FE FF, with a NUL and bytes that are not text in the middle. See the next section about byte buffers in the tutorial Binary files.
Reading#
GetValue(name, default) gives the data in the form that fits its kind — a Ring number for DWord and QWord, a text for String, a list (toList()) for MultiString — or the default when the name does not exist. GetValueKind(name) tells the kind, GetValueNames() lists the names and GetSubKeyNames() lists the sub-keys, and ValueCount counts the values. The program sorts the names, because the order of the Registry is not defined. Always give a default: a program that reads a value that is not there yet (the first run, a different version) must still work.
Cleaning up#
DeleteValue(name) removes one value, DeleteSubKeyTree(path) the key with everything inside it. The second argument False means no error when the key is missing, which the program uses to remove a key left by an earlier run. Always clean up what a test or a sample wrote: the Registry has no recycle bin, and old keys stay for ever.
Rules for programs that use the Registry#
- Write only under
HKCU\Software\<your company>\<your program>. Never change keys of other programs or of Windows. - Do not store secrets in plain text: any program of the same user can read HKCU. Use the Data Protection API (the tutorial Protecting data) or the Windows credential store.
- Read with a default and handle an invalid value; users and other tools edit the Registry.
- Do not put data there that is big (a few kilobytes is fine, megabytes are not): use a file (the tutorial Files and folders).
- Prefer a settings file when the program must also run on Linux or macOS, or when you want the user to copy the settings to another computer (the tutorial Configuration).
- Programs that start with Windows use the key
Software\Microsoft\Windows\CurrentVersion\Run: add an entry only when the user asked for it, and remove it when the program is uninstalled.
Changing the Registry can break programs and sometimes Windows. Use only your own keys, check each path before you delete, and never run code from the internet that edits the Registry.
What you learned#
- the Registry is a tree of keys and values; HKCU is yours,
CreateSubKey,OpenSubKey,SetValue,GetValue,GetValueKind,- the value kinds and how they come back in Ring,
- listing and deleting, and cleaning up,
- the rules for a program that writes there.
Exercises#
- Write a small class
Settingswithload()andsave()that keeps a list of values (name, value) in a key. - Read the version of Windows from
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion(ProductName,CurrentBuild); it is read-only for you. - Count how many sub-keys
HKCU\Softwarehas. - Write the position and size of a window of the tutorial Your first window when it closes and restore them at the next start.
Where to go next#
This was the last tutorial of the chapter Processes and performance. The next chapter is Networking and the web: it starts with Network tools. The Tutorials page lists all the chapters, and you can start any of them.