Can't read key from registry - delphi

I heared that Windows creates a unique key for a PC which is called "MachineID". I found two locations in my registry. Only the location "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" should be correct. I try to read the value by this function:
Function GetMaschineID:string;
var
Reg : TRegistry;
//HKEY_CURRENT_USER\Software\Microsoft\MSNMessenger = {dd239a44-fa0d-43ff-a51c-5561d3e39de3}
//HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography = a06b0ee0-b639-4f55-9972-146776bcd5e4
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.Rootkey:=HKEY_LOCAL_MACHINE; //Hauptschlüssel
//Reg.RootKey:=HKEY_CURRENT_USER;
if Reg.OpenKey('SOFTWARE\Microsoft\Cryptography\',false) then //Unterschlüssel öffnen
//if Reg.OpenKey('Software\Microsoft\MSNMessenger\',false) then //Unterschlüssel öffnen
begin
Result:=Reg.ReadString('MachineGuid');
end;
finally
Reg.Free;
end;
end;
This version results in an empty string; you see as comment the result from the registry. The second version for "hkey_Current_user" brings the expected string result.
What is wrong with my code or are parts of the registry read protected?

Possible explanation 1
For HKLM you are subject to registry redirection. You have a 32 bit process and are trying to read a key from the 64 bit view of the registry. By default, your 32 bit process is redirected to the 32 bit view, which (implementation detail) lives under Wow6432Node.
Use the KEY_WOW64_64KEY access flag to read from the 64 bit view. As detailed here: How can I read 64-bit registry key from a 32-bit process?
Possible explanation 2
Your call to OpenKey fails for keys under HKLM because you are requesting write access and standard user does not have write access to HKLM. Use OpenKeyReadOnly instead.
Other advice
At the very least you should have debugged this a bit more. Does the call to Reg.OpenKey succeed or fail? You should have debugged enough to know that. Perhaps you did but did not say. If Reg.OpenKey failed then explanation 2 is most likely. Even then, you may subsequently suffer from the other problem.
Note also that your function does not assign to the function result variable, or raise an error, if the call to Reg.OpenKey fails. I would expect that the compiler would have warned you about that.

procedure TForm1.Button1Click(Sender: TObject);
var
registry: TRegistry;
begin
Registry := TRegistry.Create(KEY_READ OR KEY_WOW64_64KEY);
try
registry.RootKey := HKEY_LOCAL_MACHINE;
if (registry.KeyExists('\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL')) and
(registry.OpenKeyReadOnly('\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL')) then
begin
showmessage(registry.ReadString('SQLEXPRESS'));
registry.CloseKey;
end
else showmessage('failed');
finally
registry.Free;
end;
end;

Related

please, how to code start-up behaviour in Delphi6?

I have an application, and I put a shortcut to it inside win+startup folder, and all is ok.
Now I wish to change this approach, by coding it, and so I have used the code listed at the bottom of this post.
The code inputs a key inside HKLM, but there is a windows error when system starts:
Access violation at address 004815EB in module 'ap1.exe'. Read of address 00000000.
This error is similar on 3 different computers, running win xp or win 7.
procedure SetAutoStart(AppName, AppTitle: string; bRegister: Boolean);
const RegKey = '\Software\Microsoft\Windows\CurrentVersion\Run'; // Run or
RunOnce
var Registry: TRegistry;
begin
Registry := TRegistry.Create;
try Registry.RootKey := HKEY_LOCAL_MACHINE;
if Registry.OpenKey(RegKey, False)
then begin
if bRegister = False then Registry.DeleteValue(AppTitle)
else Registry.WriteString(AppTitle,
AppName);
end;
finally Registry.Free;
end;
end;
The error is raised by the program that is executed on startup. It has nothing at all to do with the code in the question. You can verify that the code in the question behaves as expected by checking the registry entries using the Registry Editor.
You will need to debug the program that is being executed at startup. You won't be able to attach an interactive debugger. Instead you will need to use trace debugging.

Delete RegistryKey Win64/32

I am trying to delete a Windows key using Delphi , however unsuccessfully , follows the code I'm using
Function DeleteKeyAPI(hRoot: HKEY; sPath: String; IsReg64: BOOL): BOOL;
Var
iRet: Integer;
Begin
If IsReg64 Then
iRet := RegDeleteKeyEx(hRoot, PChar(sPath), KEY_WOW64_64KEY, 0)
Else
iRet := RegDeleteKeyEx(hRoot, PChar(sPath), KEY_WOW64_32KEY, 0);
If iRet = ERROR_SUCCESS Then
Result := True
Else
Result := False;
End;
in some keys I can delete more than one has in own Regedit me of an access denied error
how can I fix this problem ?
Edited -----------------------
I tried to do as follows , but without success
function SHDeleteKey(key: HKEY; pszSubKey: LPCTSTR): DWORD; stdcall;
implementation
{$R *.dfm}
function SHDeleteKey; external 'shlwapi.dll' name 'SHDeleteKeyA';
procedure TForm1.FormCreate(Sender: TObject);
begin
SHDeleteKey(HKEY_LOCAL_MACHINE, 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run\AdobeCS6ServiceManager');
end;
You should inspect the value of iRet to learn more. This is a Win32 error code that will give more details of the reason for failure.
From the documentation:
The subkey to be deleted must not have subkeys. To delete a key and all its subkeys, you need to enumerate the subkeys and delete them individually. To delete keys recursively, use the RegDeleteTree or SHDeleteKey function.
This is one common failure mode, namely that the subkey you are attempting to delete has subkeys itself. I'm not sure what error code is, perhaps ERROR_DIR_NOT_EMPTY.
Another common failure mode is that the named subkey does not exist. That would lead to error code ERROR_PATH_NOT_FOUND or perhaps ERROR_FILE_NOT_FOUND.
Finally, and what I guess is the real problem, you cannot obtain delete rights to the key. Since you are using alternate registry flags, I suspect you are trying to delete a subkey under HKLM. Your process needs sufficient rights to be able to do this. Typically that means running as an elevated admin user. You will get ERROR_ACCESS_DENIED if you have insufficient rights.
Regarding your edit, AdobeCS6ServiceManager is a value rather than a key. The function you need is RegDeleteValue. Read about the registry to learn what these terms mean: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724182.aspx
Furthermore, it is disappointing that you ask a question about RegDeleteKeyEx and then edit to show code that calls SHDeleteKey. Please try to stick to the original question.

TRegistry - why are some keys readible and others not?

I have written the following code:
var
MainForm: TMainForm;
const
SRootKey = HKEY_LOCAL_MACHINE;
SKey = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles';
implementation
{$R *.dfm}
{ TMainForm }
procedure TMainForm.GetKeys(OutList: TStrings);
var
Reg: TRegistry;
begin
OutList.BeginUpdate;
try
OutList.Clear;
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := SRootKey;
if (Reg.OpenKeyReadOnly(SKey)) and (Reg.HasSubKeys) then
begin
Reg.GetKeyNames(OutList);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
finally
OutList.EndUpdate;
end;
end;
procedure TMainForm.btnScanClick(Sender: TObject);
begin
GetKeys(ListBox1.Items);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
GetKeys(ListBox1.Items);
end;
This does not seem to do anything.
I can verify the registry path (Windows 8.1), I have even changed the SKey for testing and no issues, but certain keys like this one return nothing.
I even tried running the program from Windows as Administrator and still nothing.
Is there something else I need to change? What would make certain keys readible and others not?
Your process is 32 bit, and you are running it on a 64 bit machine. As such you are subject to registry redirection.
The registry redirector isolates 32-bit and 64-bit applications by providing separate logical views of certain portions of the registry on WOW64. The registry redirector intercepts 32-bit and 64-bit registry calls to their respective logical registry views and maps them to the corresponding physical registry location. The redirection process is transparent to the application. Therefore, a 32-bit application can access registry data as if it were running on 32-bit Windows even if the data is stored in a different location on 64-bit Windows.
The key you are looking at
HKLM\SOFTWARE
is redirected. From your 32 bit process, attempts to open this key are redirected to the 32 bit view of the registry, which as an implementation detail, is stored at
HKLM\SOFTWARE\Wow6432Node
What you are trying to do here is to access the 64 bit view of the registry. To do so you need to access an alternate registry view. That means passing the KEY_WOW64_64KEY key when opening any keys.
In Delphi you can achieve that by including KEY_WOW64_64KEY in the Access flags, or by including it in the flags you pass to the constructor.
Reg := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
On top of that, for this particular key, due to the registry security configuration for this key, you need to be running with admin rights in order to open the key. Even if you only intend to read it.

run program with administrator access to write to registery

i tried to use this tutorial to work:
https://stackoverflow.com/a/14710803/1149172
first create a file with name uac.manifest with provided content
then create uac.rc width content of 1 24 "uac.manifest"
then copied the files to program folder (in delphi program sources folder) and changed the project file like this:
program Project4;
{.$R 'uac.res' 'uac.rc'} // UAC only
uses
Vcl.Forms,
Unit6 in 'Unit6.pas' {Form6};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TForm6, Form6);
Application.Run;
end.
at last i put my registery code at the form
procedure AddEntryToRegistry;
var key: string;
Reg: TRegIniFile;
begin
key := 'Software\Microsoft\Windows\CurrentVersion\Run';
Reg := TRegIniFile.Create;
try
Reg.RootKey:=HKEY_LOCAL_MACHINE;
Reg.CreateKey(Key);
if Reg.OpenKey(Key,False) then Reg.WriteString(key, 'MyApp', 'c:MyApp.exe');
finally
Reg.Free;
end;
end;
every thing seems ok and i dont got any runtime rror
but after clicking the button nothing happened (dont shoe any error and dont add the key to registery)!!!
where is wrong with my works!?
my delphi is xe5 and working on win 8ul
Firstly, I'm going to take it as read that your program is running elevated. If that's not happening then there's no need to look at any code. You did not say otherwise, so let us proceed under the assumption that you are succeeding to elevate.
You are suffering from the registry redirector. Your 32 bit process is running on a 64 bit machine. And so HKLM\Software is redirected to the 32 bit view, stored at HKLM\Software\Wow6432Node.
You can, if you need, use the KEY_WOW64_64KEY flag to access the 64 bit view. Combine this with the flags in the registry object's Access property.
However, the system reads keys from both 32 and 64 bit views of the registry when enumerating the startup programs so you do not need to do this. For the sake of simplicity and predictability I would leave your 32 bit program writing to the 32 bit view.
Your call to CreateKey should be removed. The system creates that key and you can safely assume it exists. And you should not use TRegIniFile. Use TRegistry instead.
Your code should look like this:
procedure AddEntryToRegistry;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_ALL_ACCESS);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False) then
Reg.WriteString('MyApp', 'C:\MyApp.exe');
finally
Reg.Free;
end;
end;
Should you feel that you need to write to the 64 bit view then it is done like this:
procedure AddEntryToRegistry;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.Access := KEY_ALL_ACCESS or KEY_WOW64_64KEY;
if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False) then
Reg.WriteString('MyApp', 'C:\MyApp.exe');
finally
Reg.Free;
end;
end;
Judging by your comments, it looks like you might be failing to elevate. The lack of a UAC dialog when your program starts is the tell-tale sign that this is happening. Once your program starts without a UAC dialog, there's no point continuing. You will not write to HKLM without elevation.
Regarding your manifest, you can link only one. So if you want to specify a manifest other than the Enable runtime themes manifest that the IDE can provide, you need to do it all yourself.
In the project options specify that you want to use a custom manifest. That's under Project | Options | Application | Runtime themes. Set the drop down to Use custom manifest. And then supply the file name of your manifest. You'll want to add in the comctl32 v6 part to make sure that you get runtime themes. But don't worry about that now. Just concentrate on getting elevation sorted, and the registry code working.
You are also silently ignoring any errors which does make things a little harder to debug. If it so happens that you are not elevating, then running the code is rather pointless. You know it must fail. But you could at least make it easier to diagnose the problem by throwing an error if OpenKey fails.
procedure AddEntryToRegistry;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_ALL_ACCESS);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if not Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False) then
raise EMyExceptionClass.Create('Could not open registry key');
Reg.WriteString('MyApp', 'C:\MyApp.exe');
finally
Reg.Free;
end;
end;
One final point to make is that writing to this registry key is an admin task. You should require elevation once only, not every time your application starts. If you are planning to require elevation for your application just for this purpose, then you must re-design. This admin task should be performed outside your main application. The most natural place is inside your install program which users will accept requiring elevation.
You are saving your app path to the Run key of the HKEY_LOCAL_MACHINE hive. You should be using the HKEY_CURRENT_USER hive instead, then you will not need to use UAC elevation anymore (unless your app is doing other things that require admin rights).

SHDeleteKey Function

I am having one Delphi XE2 Project for Windows Registry Operation. I need to delete all subnodes under **HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000001}** , so I have defined the following codes :
function SHDeleteKey(key: HKEY; SubKey: PWideChar): Integer; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW';
..
..
..
..
..
procedure TMainForm.BitBtn02Click(Sender: TObject);
var
RegistryEntry : TRegistry;
begin
RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
RegistryEntry.RootKey := HKEY_CLASSES_ROOT;
if (RegistryEntry.KeyExists('CLSID\{00000000-0000-0000-0000-000000000001}\')) then
begin
Memo01.Font.Color := 3992580;
Memo01.Lines.Add('Windows Registry Entry Has Been Found In Your System');
RegistryEntry.Access:= KEY_WRITE or KEY_WOW64_64KEY;
SHDeleteKey(HKEY_CLASSES_ROOT, PWideChar('CLSID\{00000000-0000-0000-0000-000000000001}'));
RegistryEntry.CloseKey();
RegistryEntry.Free;
Memo01.Font.Color := 16756480;
Memo01.Lines.Add('Windows Registry Entry Has Been Deleted Successfully');
end
else
begin
Memo01.Font.Color := 7864575;
Memo01.Lines.Add('Windows Registry Entry Has Not Been Found In Your System');
end;
end;
But nothing is happening. Then I have tried
function SHDeleteKey(key: HKEY; SubKey: PChar): Integer; stdcall; external 'shlwapi.dll';
but here is another problem is telling "Entry Point not found".
Your function import is failing because the function is named SHDeleteKeyW where the W specifies that you want to use Unicode characters. So your function declaration should be
function SHDeleteKey(hKey: HKEY; pszSubKey: PWideChar): Integer; stdcall;
external 'shlwapi.dll' name 'SHDeleteKeyW';
Once that is fixed, the two most common failure modes are:
Your process does not have admin rights.
Your process runs in a 32 bit process on a 64 bit system and so cannot see the 64 bit view of the registry.
Based on your earlier question, option 2 seems most likely.
You said "nothing is happening", but I'm sure something is happening. The function is failing and returning an error status to you. But you did not check the return value of the call to SHDeleteKey. Whenever you call a Windows API, check the return value. If it fails, the return value allows you to diagnose that failure.
Assuming the issue is the registry redirector for your 32 bit process, your options include:
Run the code from a 64 bit process.
Use RegDeleteTree.
Empty the key's subkeys first, and then use TRegistry.DeleteKey.
Note that the code where you specify KEY_WOW64_64KEY only has effect when using the TRegistry methods. Since SHDeleteKey is a Windows API function, it is independent from that class.
For your second problem, you may want to try ShDeleteKeyW instead (explicitly selecting the wide string variant).
In both cases, however, you should check the result to see why it failed.
You don't mention what O/S this is on but there appears to be several platform-specific quirks with this function as can be seen in the comments here.

Resources