RingDotNetfor Ring

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 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#

samples/UsingDotNet/tutorials/ch06_registry.ring
# 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()
Output
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: 1
Note

This 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:

KindDataUse
Stringtextnames, paths
DWorda 32-bit whole numbersizes, flags, counters
QWorda 64-bit whole numberbig numbers (5 000 000 000 does not fit 32 bits)
MultiStringa list of textsa list of recent files
ExpandStringtext with %NAME% variablesa path such as %USERPROFILE%\Data: GetValue gives the text with the variable already replaced
Binarybytespictures, 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#

Warning

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#

Exercises#

  1. Write a small class Settings with load() and save() that keeps a list of values (name, value) in a key.
  2. Read the version of Windows from HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion (ProductName, CurrentBuild); it is read-only for you.
  3. Count how many sub-keys HKCU\Software has.
  4. 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.

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.