Enumerate registry subkeys in delphi

南楼画角 提交于 2021-01-22 04:26:13

问题


I'm attempting to install a driver on a client machine based on which version of MySQL is installed on the server and to do that I'd like to check the version on the server via registry key.

That said, I need to enumerate the subkey(s) of HKEY_LOCAL_MACHINE\SOFTWARE\MySQL AB. There is usually just one key under this one and it is generally of the form: MySQL Server #.#, where # stands for a number.

But because I don't know which value those are, is there a way to get the key and then I can get the numbers from the name to determine which driver to install? I'm thinking that enumerating the subkeys is the best way to get the key, but perhaps a clever string formatting and loop would work too?


回答1:


The best solution is to enumerate the sub keys. Using RegEnumKeyEx you just do that in a simple loop until there are no more keys left to enumerate.

However, enumerating sub keys in Delphi using TRegistry is even easier still:

program _EnumSubKeys;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Windows, Registry;

procedure EnumSubKeys(RootKey: HKEY; const Key: string);
var
  Registry: TRegistry;
  SubKeyNames: TStringList;
  Name: string;
begin
  Registry := TRegistry.Create;
  Try
    Registry.RootKey := RootKey;
    Registry.OpenKeyReadOnly(Key);
    SubKeyNames := TStringList.Create;
    Try
      Registry.GetKeyNames(SubKeyNames);
      for Name in SubKeyNames do
        Writeln(Name);
    Finally
      SubKeyNames.Free;
    End;
  Finally
    Registry.Free;
  End;
end;

begin
  EnumSubKeys(HKEY_LOCAL_MACHINE, 'Software\Microsoft');
  Readln;
end.

One thing that you should watch out for is having to search in the 64 bit view of the registry. If you have the 64 bit version of MySQL installed then I expect it to use the 64 bit view of the registry. In a 32 bit Delphi process on a 64 bit OS you will need to side step registry redirection. Do that by passing KEY_WOW64_64KEY to the TRegistry constructor.


The alternative that you propose is to hard code all the possible values of version string into your application. That sounds like a failure waiting to happen as soon as a version is released which isn't in your hard coded list.



来源:https://stackoverflow.com/questions/9004870/enumerate-registry-subkeys-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!