How to Use the Windows Registry to Save Data Table Records

Saving To-Do List Data Items in the Windows Registry Allows Interactive Realtime Updates from the GUI ListView Control

ToDoListReg

The GUI ListView control acts like a data table (i.e. interactive rows and columns). The ListView control includes a number of functions for adding, inserting, modifying and deleting rows and columns,—plus, even more functions for sorting and selecting rows, as well as, retrieving data. I’ve used the AutoHotkey ListView control for a to-do list (shown at right), an address book,  a calorie counting app and listings of icon images embedded in files. (I consider all of these apps educational tools or starting points for AutoHotkey scripting—not final products.)

The AutoHotkey ListView control operates in the same manner as Windows File Explorer—automatically sorting on clicked column headers with editing available in the first field of the selected row on a second click. When included in a GUI (Graphical User Interface), the control adds a great deal of flexibility to any data table display, but it does not automatically save the data. You must write that code yourself.

coverepub-250

In “Chapter Nine: A Daily To-Do List App (ListView GUI Control and Saving a Data File)” along with “Chapter Ten: More To-Do List App (Resizing and Positioning the GUI)” of the book AutoHotkey Applications: Ideas and Tips for Writing Practical AutoHotkey Scripts, I introduced my first ToDoList.ahk script as a way to demonstrate how to use the GUI ListView control. While the script does the job and offers numerous AutoHotkey techniques, I never felt the script quite robust enough.

When saving data to the text file, the script first deletes the old file then rewrites it using the current data found in the ListView. If something unusual occurs, all data gets trashed leaving a blank To-Do List window. Since (with two exceptions) AutoHotkey offers no special tools for editing or deleting individual records in a data file, whenever saving, the script needs to completely rewrite the file. This creates the source of the potential wipeout problem. If available, data management tools for working with text files would make adding, inserting, editing, updating, and deleting records easy. However, in AutoHotkey, which operates without those utilities, the entire data file must be rewritten for any event other than adding a new record (FileAppend command) to the end of the file.

Library Benefits

In the original ToDoList.ahk script, no links exist between the individual ListView rows and the records in the data file. On loading, AutoHotkey reads the entire data file into the ListView control, then rewrites the file after changes occur—except when appending new records. Since AutoHotkey doesn’t offer techniques for inserting or deleting records in the middle of a text file, interaction on a record level presents an awkward problem.

However, AutoHotkey does include two alternatives to the standard text file as possible solutions for this cumbersome data-manipulation problem:

  1. Use an INI file to save data. AutoHotkey includes built-in INI file commands that allow the updating of individual records without rewriting the entire file. (AutoHotkey takes care of the file handling in the background.) An INI file can act as a data table file allowing access to individual entries without affecting anything else.
  2. Use the Windows Registry as a data table.  AutoHotkey includes built-in Windows Registry commands that allow the updating of registry entries without touching any other data. The Windows Registry can act as a data table with direct access to individual entries.

I’ve chosen to start with the ToDoListReg.ahk script which demonstrates techniques for saving and accessing settings and data in the Windows Registry. Later, I plan to do the same for INI files.

Note: This new to-do list script uses many GUI ListView techniques discussed in the AutoHotkey Applications book. This blog concentrates on the AutoHotkey Windows Registry commands and the techniques required to turn the registry into a mini-data table for the ToDoListReg.ahk script. The critical changes include adding a new ListView column (RegRec) for relating the ListView row to a registry record.

Caution: While the Windows Registry offers an excellent method for storing settings and limited data items, such as those used in the ToDoListReg.ahk script, I don’t recommend setting up the registry for applications requiring a vast number of data records. (For that type of application, you should look into software designed for database management.) The Windows Registry is the backbone of the Windows operating system. Take care when using it. Randomly tromping around in the unknown can cause unexpected problems.

For example, when picking an area of the registry to save data, ensure you don’t accidentally settle upon occupied addresses. (Check it out with RegEdit first!) Generally, using the Registry Key HKEY_CURRENT_USER (HKCU) will isolate the data from the more dangerous sections that could cause either program or system instability. You’ll find the limited techniques offered here safe enough but look before you leap.

The Data Table Problem

While the GUI ListView control includes functions for handling rows and columns in a data table, saving records to a data table file must occur in an organized fashion—allowing easy retrieval, editing, updating, and deletion. That means assigning a unique identifier to each record in the saved file and connecting it to the appropriate row in the ListView table (RegRec). One of the easier methods applies sequential alphanumeric keys for retrieving information from the drive. This approach makes the use of those embedded numbers in loops easier.

Unlike the ListView control itself, adding new records to the saved data table makes the file grow while deleting records in that same file creates gaps in the numeric order. (Some database languages do not delete records but rather mark the file records “deleted” so they no longer appear when copied to the interface. A later cleanup procedure removes the “deleted” records from the file.)

In my data table file system, I don’t delete any records. I merely mark the record as deleted by removing all text. The script ignores blank entries. Later, when adding new items, the script reuses the blank records. That prevents the data table file from growing beyond what’s needed. Plus, when deleting data, holes do not pop-up in the sequential numbering system. For those reasons, I do not use the delete command (IniDelete or RegDelete). The new ToDoListReg.ahk script only uses the RegWrite and RegRead commands.

Data Manipulation Commands

AutoHotkey includes commands which allow reading and writing individual records for both INI files and the Windows Registry without recreating a new file. These data table management tools make reading and saving records easier. In both cases, the commands allow direct access to individual records. But, to take advantage of these capabilities, you must build a data structure that responds to your application—in particular (as mentioned above), creating special record identifiers (RegRec) for attaching each ListView row to the proper saved record (e.g. Item1, Item2, Item3, …).

ToDoRegistry
The hidden RegRec column in the ListView contains the name of the corresponding Windows Registry ToDoListItem entry.

Writing Data Records

The AutoHotkey IniWrite command makes it possible to insert data items directly into an INI text file without dealing with the file rewriting process. Of course, the system automatically updates the file with each change, but that’s built-into the system:

IniWrite, Value, Filename, Section, Key

The AutoHotkey RegWrite command provides direct access for saving data in the Windows Registry:

RegWrite, ValueType, KeyName , ValueName, Value

Reading Data Table Records

Later, when we need to access the saved data, the IniRead command allows the retrieval of specific values from the INI file:

IniRead, OutputVar, Filename, Section, Key , Default

As with the INIRead command, the RegRead command gives the AutoHotkey script a direct connection to specific records based upon the item’s alphanumeric name:

RegRead, OutputVar, KeyName , ValueName

While the basic structure and the ListView tricks in the original ToDoList.ahk script have changed little, in this new ToDoListReg.ahk script, I replaced all file writing and reading activities with the appropriate RegWrite and RegRead commands.

Reading (or Writing) Loops

Any new ToDoList.ahk scripts still require loops for loading data into the ListView control along with other special saving and cleanup activities. INI files do not include dedicated looping commands but you can use either the standard Loop command or Loop (parse a string) command:

Loop, Parse, InputVar [, Delimiters, OmitChars]

AutoHotkey includes a built-in Loop (Registry) command for skipping through sections of the Windows Registry:

Loop, Reg, KeyName, Mode

Note: AutoHotkey coders must understand that the Loop, Reg command works in reverse order and that the sort may not follow the same sequence as the entries displayed in the Windows RegEdit utility. For example, the RegEdit window shows a purely alphabetic sort (Item10 appears immediately after Item1 but before Item2) while the Registry Loop uses an alphanumeric sort (Item10 appears at the end of the list after Item9). The reverse order loop allows the deletion of entries without affecting the remainder of the loop.

Saving Data to the Windows Registry

While either table data saving approach would work (INI file or Windows Registry), the INI file requires the script to keep track of a separate file. If we use the Windows Registry, the script works without requiring a separate data file. Plus, when using the registry, the working or script loading directory location becomes irrelevant. However, the script does need additional logic for completing the data table management.

Saving the Last ToDoListReg.ahk Window Position

The script uses a separate Windows Registry entry to save the last position and size of the window with the OnExit command.

ToDoRegistryPos.png

While I don’t include the entire script in this blog (you can find it at the Free AutoHotkey Scripts page), the following snippets of code show the changes in the basic subroutines (highlighted in red).

Loop for Loading To-Do List Items into ListView

Loop, Reg, HKCU\Software\ToDoListItem , KV
{
  RegRead, value, HKCU\Software\ToDoListItem , %A_LoopRegName%
  If (value != "" and InStr(A_LoopRegName,"Item"))
    If SubStr(value, 1, 1) = "√"
    {
      StringTrimLeft, CheckedText, value, 1
      LV_Add("Check", CheckedText, A_LoopRegName)
    }
    Else
      LV_Add("", value, A_LoopRegName)
}

Subroutine for Adding a New To-Do List Item

AddItem:

Gui, Submit, NoHide
NextItem := ""
Count := 1
Loop, Reg, HKCU\Software\ToDoListItem , KV
{
  RegRead, value
  If (value = "" and NextItem = "" and InStr(A_LoopRegName,"Item")) {
    NextItem := A_LoopRegName
    Break
  }
  Count++
}
If (NextItem = "") {
  NextItem := "Item" . Count
}
RegWrite, REG_SZ, HKCU\Software\ToDoListItem, %NextItem%, %NewItem%
LV_Add("", NewItem, NextItem)
LV_ModifyCol(1, "Sort")
LV_ModifyCol(1,"AutoHdr")

Return

Subroutine for Editing To-Do Items

MyListView:
If A_GuiEvent = e
{
  LV_GetText(ItemText, A_EventInfo)
  LV_GetText(ItemNumber, A_EventInfo, 2)
  LV_ModifyCol(1, "Sort")
  LV_ModifyCol(1,"AutoHdr")
  RegWrite, REG_SZ, HKCU\Software\ToDoListItem, %ItemNumber%, %ItemText%
}
Return

Subroutine for Deleting To-Do Items

DeleteItem: ; The user selected "Delete" in the context menu.
  SelectedRow := LV_GetNext()
  ItemText := ""
  LV_GetText(ItemNumber, SelectedRow, 2)
  RegWrite, REG_SZ, HKCU\Software\ToDoListItem, %ItemNumber%, %ItemText%
  LV_Delete(SelectedRow)
Return

A few important changes which appear in the script but not in this blog include:

  1. The script does not save the status of a checked (or not) item until closing the window or exiting the app. This compromise allows the continued use of the one-click editing in the ListView per the current “Tip of the Week.”
  2. The item numbers must occur sequentially in the Windows Registry without gaps. In case of missing item entries, the same closing subroutine which adds and removes the checkmarks also cleans up the registry.
  3. While the script records the current window position and dimensions upon exiting the app, no updates occur for a minimized window.

You can also find this ToDoListReg.ahk script posted on the AutoHotkey Forum.

I expect that in one or more blogs I will address the peculiarities of the AutoHotkey registry commands found in each of the above snippets. But, first, I plan to write another form of the to-do list script using an INI file as a data table. I will then compare the two scripts—highlighting the similarities and differences.

Since I spend a great deal of time discussing how to use the multitude of the ListView functions shown above in numerous chapters of the AutoHotkey Application book, I don’t plan to detail how they work in these to-do list blogs.

Click the Follow button at the top of the sidebar on the right of this page for e-mail notification of new blogs. (If you’re reading this on a tablet or your phone, then you must scroll all the way to the end of the blog—pass any comments—to find the Follow button.)

jack

This post was proofread by Grammarly
(Any other mistakes are all mine.)

(Full disclosure: If you sign up for a free Grammarly account, I get 20¢. I use the spelling/grammar checking service all the time, but, then again, I write a lot more than most people. I recommend Grammarly because it works and it’s free.)

 

 

4 thoughts on “How to Use the Windows Registry to Save Data Table Records

  1. Very nice. I just discovered the ini functions myself and just started using them for similar reasons. You post expands upon my efforts and gives me an idea. Do you know if there are any functions to allow Autohotkey to interface with sqlite? I have a number of apps that use sqlite and it would be nice to be able to read/write data from ahk apps.

    Thanks for the blog!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s