How to access the Registry using Windows API #14
You may, for some reasons not want to use Delphi's TRegistry component but still want to use the system's registry. This may come in handy when creating applications for Windows NT/2000/XP. Delphi's TRegistry component may raise an error when attempting to write a string value to the HKEY_LOCAL_MACHINE key. Well, the way to get over this is to call the Windows API directly. This is a little harder than using the TRegistry component, but Delphi users that have some C/C++ experience shouldn't have any problems. If you like Object Pascal's standard data types you're going to hate this ;-) Although this may look like a lot of work it's really fun. When your program saves/reads a lot of data to/from the registry (like Option dialogs) this may dramatically shorten the time needed for these operations.
This example will not work on Windows 3.x with Win32s installed because the API functions used here are native Win32 functions. Check up the function parameters in the Win32 help.
The API functions we will need:
- RegCreateKeyEx() or RegOpenKeyEx()
- RegCloseKeyE()
- RegSetValueEx()
uses Windows; ... var hOpenKey: HKEY; iI, iSize, iType: Integer; pcTemp: PChar; pdI: PDWORD; ... begin ... { This example creates and opens the key HKEY_CURRENT_USER\Software\m3Rlin\Delphi FAQ and saves data in it. If you don't want to create a key but just open an existing one use the RegOpenKeyEx() function. } pdI := nil; if RegCreateKeyEx(HKEY_CURRENT_USER, 'Software\m3Rlin\Delphi FAQ', 0, nil, REG_OPTION_NON_VOLATILE, KEY_WRITE, nil, hOpenKey, pdI) = ERROR_SUCCESS then begin // Saving a Boolean value iI := Integer(checkboxMain.Checked); RegSetValueEx(hOpenKey, 'Boolean Value', 0, REG_DWORD, @iI, SizeOf(iI)); // Saving a Integer value iI := Integer(MainForm.Height); RegSetValueEx(hOpenKey, 'Integer Value', 0, REG_DWORD, @iI, SizeOf(iI)); // Saving a string value RegSetValueEx(hOpenKey, 'String Value', 0, REG_SZ, PChar(MainForm.Caption), Length(MainForm.Caption) + 1); // The 1 is for the terminating 0 (PChar) RegCloseKey(hOpenKey); // Close the open registry key end; ... { This example opens the key HKEY_CURRENT_USER\Software\m3Rlin\Delphi FAQ and reads data from it. } pdI := nil; if RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\m3Rlin\Delphi FAQ', 0, KEY_READ, hOpenKey) = ERROR_SUCCESS then begin // Reading an Integer value iType := REG_DWORD; // Type of data that is going to be read iSize := SizeOf(Integer); // Buffer for the value to read if RegQueryValueEx(hOpenKey, 'Integer Value', nil, @iType, @iI, @iSize) = ERROR_SUCCESS then MainForm.Height := iI; // Reading a string value if RegQueryValueEx(hOpenKey, 'String Value', nil, @iType, pcTemp, @iSize) = ERROR_SUCCESS then MainForm.Caption := string(pcTemp); RegCloseKey(hOpenKey); end; ... end;
Author: | Unknown |
---|---|
Added: | 2007/06/02 |
Last updated: | 2007/06/02 |