views:

969

answers:

4

The following code sample used to return me windows id before, but now it doesn't work, and returns empty string, dunno why.

  function GetWindowsID: string;
  var
    Registry: TRegistry;
    str:string;
  begin
    Registry := TRegistry.Create(KEY_WRITE);
    try
      Registry.Lazywrite := false;
      Registry.RootKey := HKEY_LOCAL_MACHINE;
   //   Registry.RootKey := HKEY_CURRENT_USER;
      if CheckForWinNT = true then
       Begin
       if not Registry.OpenKeyReadOnly('\Software\Microsoft\Windows NT\CurrentVersion') then showmessagE('cant open');
       end
      else
        Registry.OpenKeyReadOnly('\Software\Microsoft\Windows\CurrentVersion');
      str := Registry.ReadString('ProductId');
      result:=str;
      Registry.CloseKey;
    finally
      Registry.Free;
    end; // try..finally
  end;

Anybody can help?

+1  A: 

I'd say that this is caused by UAC - try starting as administrator!

If it works when started as administrator, then you need to change your read request to use read only mode (not at desk at mo so can't remember exactly how you do that)

edit:

function GetWindowsID: string; 
var 
  Registry: TRegistry; 
  str:string; 
begin 
  Registry := TRegistry.Create(KEY_READ); 
  try 
    Registry.RootKey := HKEY_LOCAL_MACHINE; 
 //   Registry.RootKey := HKEY_CURRENT_USER; 
    if CheckForWinNT = true then 
     Begin 
     if not Registry.OpenKeyReadOnly('\Software\Microsoft\Windows NT\CurrentVersion') then showmessage('cant open'); 
     end else 
       Registry.OpenKeyReadOnly('\Software\Microsoft\Windows\CurrentVersion'); 
    str := Registry.ReadString('ProductId'); 
    result:=str; 
    Registry.CloseKey; 
  finally 
    Registry.Free; 
  end; // try..finally 
end; 
MarkRobinson
A: 

Try reading it manually using RegEdit. You may get 'Access Denied' due to a permission issue, in which case look at your level and how you are accessing it.

Brian Frost
+8  A: 

That is because the virtualized key '\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\' doesn't contain the 'ProductID' item.

Modify your code to create the TRegistry instance with

Registry := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY);

where KEY_WOW64_64KEY = $0100. That will give you the expected result.

Alternatively, use DSiWin32 and call

DSiReadRegistry('\Software\Microsoft\Windows NT\CurrentVersion', 
  'ProductID', '', HKEY_LOCAL_MACHINE, KEY_QUERY_VALUE OR KEY_WOW64_64KEY);
gabr
A: 

You should using this: TRegistry.Create(KEY_ENUMERATE_SUB_KEYS); windows seven UAC won't prevent executing this

sam