出于某种充分的理由,我需要将二进制值的字符串格式写入二进制注册表项,换句话说,我有一个如下所示的注册表值:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Sonal]
"Password"=hex:00,d6
我尝试使用以下代码将其写入注册表:
procedure Tesct.Button2Click(Sender: TObject);
var
RegInfoExists : TRegistry;
EdStr : AnsiString;
begin
try
RegInfoExists := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY);
RegInfoExists.RootKey := HKEY_LOCAL_MACHINE;
if RegInfoExists.OpenKey('SOFTWARE\Sonal',true) then
EdStr := #$00#$d6;
RegInfoExists.WriteBinaryData('Password', EdStr,
Length(EdStr) * SizeOf(byte));
except
end;
RegInfoExists.CloseKey;
RegInfoExists.Free;
end;
我得到了这个:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Sonal]
"Password"=hex:dc,d7
我怎样才能做到这一点?
最佳答案
您正在写入string
变量的值,它是字符串的地址。这是因为在实现级别,字符串只是指针。
相反,您需要取消引用指针。两种常用的方法:
RegInfoExists.WriteBinaryData('Password', EdStr[1],
Length(EdStr)*SizeOf(AnsiChar));
或
RegInfoExists.WriteBinaryData('Password', Pointer(EdStr)^,
Length(EdStr)*SizeOf(AnsiChar));
如果你真的只是想写这两个字节,那么这样更容易:
const
Password: array [0..1] of byte = ($00, $d6);
....
RegInfoExists.WriteBinaryData('Password', Password, Length(Password));
<小时/>
我还要评论说,您应该非常严格和精确地管理资源。这意味着正确使用try/finally
。像这样:
SomeInstance := TSomeClass.Create;
try
.... do stuff with SomeInstance
finally
SomeInstance.Free;
end;
而且您似乎还省略了 if
语句后面的代码所需的 begin
/end
。
关于string - 如何使用Delphi和writebinary命令将二进制值的字符串格式写入注册表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24361751/