Registry

Use registry instead of *.ini file

Posted in Registry

Ini files are necessary for a storage of an information and parameters of the programs. It is possible to do it with use a registry. This example create HKEY_LOCAL_MACHINE\Greatis Software\Example key with "First page" parameter, which stores a path to rtf file. This file will be loading from this parameter after Button2 click event. You can store boolean, time and others types of variables in registry also.

uses Registry;
...
procedure TForm1.Button1Click(Sender: TObject);
begin
  with TRegistry.Create do
  begin
   LazyWrite:=False;
   RootKey:=HKEY_LOCAL_MACHINE;
   if OpenKey('Greatis Software\Example', True) then
     WriteString('First page', 'c:\overview.rtf')
   else
     MessageDlg('Registry reading error', mtError, [mbOk], 0);
   CloseKey;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  with TRegistry.Create do
  begin
    RootKey:=HKEY_LOCAL_MACHINE;
    if OpenKey('Greatis Software\Example', False) then
    try
      RichEdit1.Lines.LoadFromFile(ReadString('First page'));
    except
      MessageDlg('Can not go to handle', mtError, [mbOk], 0);
    end
    else
      MessageDlg('Registry reading error', mtError, [mbOk], 0);
    CloseKey;
  end;
end;

Registration OCX

Posted in Registry

Before an OCX can be used, it must be registered with the System Registry. Suppose the OCX you want to use is called "test.ocx". To register this OCX use code from example below. You can the same way unregister the OCX: all you have to do is to replace 'DllRegisterServer' by 'DllUnregisterServer'. You should add some validation code: "Does the file exist", "Was the call to LoadLibrary successful?", ... Some explanations: An OCX is a special form of dll, so you can load it in memory with a call to the LoadLibrary API function. An OCX exports two functions to register and unregister the control. You then use GetProcAddress to obtain the address of these functions. You just have then to call the appropriate function. And that's it! You can explore the Registry (with regedit.exe) to verify that the OCX is registered.

var
  OCXHand: THandle;
begin
  OCXHand:=LoadLibrary('c:\windows\system\test.ocx');
  if (GetProcAddress(OCXHand,'DllRegisterServer')<>nil) then 
    ShowMessage('Error!');
  FreeLibrary(OCXHand);
end;