delhpi TRegistry

来源:互联网 发布:行知精神是什么 编辑:程序博客网 时间:2024/05/17 08:20

32位Delphi程序中可利用TRegistry对象来存取注册表文件中的信息。
  一、创建和释放TRegistry对象
  1.创建TRegistry对象。为了操作注册表,要创建一个TRegistry对象:ARegistry := TRegistry.Create;
  2.释放TRegistry对象。对注册表操作结束后,应释放TRegistry对象所占内存:ARegistry.Destroy。
  二、指定要操作的键
  操作注册表时,首先应指定操作的主键:先给属性RootKey赋值以指定根键,然后用方法OpenKey来指定要操作的主键名。
  1.指定根键(RootKey)。
  根键是注册表的入口,也注册表信息的分类,其值可为:
  HKEY—CLASSES—ROOT:存储整个系统对象类信息,如ActiveX对象注册、文件关联等信息。
  HKEY—CURRENT—USER:存储当前用户的配置信息。为属性RootKey的默认值。
  HKEY—LOCAL—MACHINE:存储当前系统的软硬件配置信息。应用程序自己的信息可以存储在该根键下。
 HKEY—USERS:存储所有用户通用的配置信息。
  还可以是HKEY—CURRENT—CONFIG、HKEY—DYN—DATA。
  2.指定要操作的主键。
  Function OpenKey(const Key: string; CanCreate: Boolean): Boolean;
  Key:主键名,是键名全名中除去根键的部分,如Software\Borland\Delphi。
  CanCreate:在指定的主键名不存在时,是否允许创建该主键,True表示允许。
  返回值True表示操作成功。
  3.关闭当前主键。
  在读取或存储信息之后,应及时将关闭当前主键:procedure CloseKey。
  三、从注册表中读取信息
  Read系列方法从注册表读取指定的信息(字符串、二进制和十六进制),并转换为指定的类型。
  1.Read系列方法。
  function ReadString(const Name: string): string;
  读取一个字符串值,Name为字符串名称。
  function ReadInteger(const Name: string): Integer;
  读取一个整数值,Name为整数名称。
  function ReadBinaryData(const Name: string; var Buffer; BufSize: Integer):Integer;
  读取二进制值,Name为二进制值名称,Buffer为接收缓冲区,BufSize为缓冲区大小,返回为实际读取的字节数。
  其它方法还有:ReadBool、ReadCurrency、ReadDate、ReadDateTime、ReadFloat、ReadTime。
  2.读取信息一例(显示Windows的版本)。
 在HKEY—LOCAL—MACHINE\Software\Microsoft\Windows\CurrentVersion下,有三个字符串值Version、VersionNumber和SubVersionNumber,用于记录当前Windows的版本号。
  {请在Uses中包含Registry单元}
  procedure TForm1.Button1Click(Sender:TObject);
  var
   ARegistry : TRegistry;
  begin
   ARegistry := TRegistry.Create;
  //建立一个TRegistry实例
   with ARegistry do
    begin
   RootKey := HKEY—LOCAL—MACHINE;//指定根键为HKEY—LOCAL—MACHINE
   //打开主键Software\Microsoft\Windows\CurrentVersion
   if OpenKey( ′Software\Microsoft\Windows\CurrentVersion′,false ) then
   begin
   memo1.lines.add('Windows版本:′+ ReadString(′Version′));
   memo1.lines.add('Windows版本号:′+ ReadString(′VersionNumber′));
   memo1.lines.add(′Windows子版本号:′+ ReadString(′SubVersionNumber′));
   end;
   CloseKey;//关闭主键
   Destroy;//释放内存
   end;
  end;
  四、向注册表中写入信息
  Write系列方法将信息转化为指定的类型,并写入注册表。
  1.Write系列方法。
  procedure WriteString(const Name, Value: string);
  写入一个字符串值,Name为字符串的名称,Value为字符串值。
  procedure WriteInteger(const Name: string; Value: Integer);
  写入一个整数值。
  procedure WriteBinaryData(const Name: string; var Buffer; BufSize: Integer);
  写入二进制值,Name为二进制值的名称,Buffer为包含二进制值的缓冲区,BufSize为缓冲区大小。
  其它方法还有:WriteBool、WriteCurrency、WriteDate、WriteDateTime、WriteFloat、WriteTime。
  2.写入信息一例。
  下面程序使Delphi随Windows启动而自动运行。
  var
   ARegistry : TRegistry;
  begin
   ARegistry := TRegistry.Create;
  //建立一个TRegistry实例
   with ARegistry do
   begin
   RootKey:=HKEY—LOCAL—MACHINE;
    if OpenKey(′Software\Microsoft\Windows\CurrentVersion\Run′,True) then
   WriteString(′delphi′,′C:\Program Files\borland\delphi3\bin\delphi32.exe′);
   CloseKey;
   Destroy;
   end;
  end;
  五、键值维护
  除了在注册表中读取、存储外,程序可能还需要增加主键、删除主键、主键改名、数据值改名等。
  1.创建新主键:function CreateKey(const Key: string): Boolean。
  Key即为主键名,返回值True表示操作成功。
  2.删除主键:function DeleteKey(const Key: string): Boolean。
  Key即为主键名,返回值True表示操作成功。
  3.复制或移动主键:procedure MoveKey(const OldName, NewName: string; Delete: Boolean)。
  OldName、NewName分别表示源主键名和目标主键名;Delete表示是否删除源主键,True表示删除,False表示保留。
  复制或移动一个主键将复制或移动该子键下的所有数据值和子键内容。
  4.判断指定主键是否存在,其下是否有主键,并获取主键名称。
  KeyExists用于判断指定主键是否存在:
  function KeyExists(const Key: string): Boolean;//返回值为True表示主键存在。
  HasSubKeys用于判断指定主键下是否有子键:function HasSubKeys: Boolean;
  返回值为True表示主键下有子键。
 GetKeyNames用于获取子键名称:procedure GetKeyNames(Strings: TStrings);
 Strings用于返回当前主键下各子键的名称。
  5.获取主键下的数据值名称:procedure GetValueNames(Strings: TStrings)。
  Strings用于返回当前主键下各数值名称。
  如要获取当前系统中的拨号连接名称,可利用获取主键HKEY—USERS \.DEFAULT\RemoteAccess\Addresses下的数值名称的方法来进行。
  6.判断数值名称存在、数值名称改名。
  ValueExists用于判断数值名称是否存在:
  function ValueExists(const Name: string): Boolean;
  返回值为True表示数值名称存在。
  RenameValue用于数值名称改名:
  procedure RenameValue(const OldName, NewName: string);
 以上是注册表常用操作所对应的TRegistry的方法和属性,其它方法和属性请参见Delphi联机帮助文件。
以上程序在PWIN 98+Delphi 3.0下调试通过。
2003-11-20 11:53:00
发表评语»»»
2003-11-20 11:59:20 注册表中对编程常用的几项(ODBC/BDE/Internet/Windows) 我用的是 WINDOWS 2000, WIN2000 的 REGEDIT 提供了类似 IE 中收藏夹的功能,我的收藏夹中有几个或许对大家编程时会有帮助(这是本人在编程过程中的探索出来的,请高手指教):
1。关于 ODBC 和 DBE:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC File DSN
有你的 COMPUTER 上 ODBC 的 FILE DSN 的存放的缺省路径,如果你建立 FILE DSN 的时候选择了自己的路径,那你就得小心了,系统不会为你保存该路径,你的自己记住它,:-(;
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers
列出了你的所有 ODBC DRIVER,
关于 ODBC DRIVER 的名称,有一个比较有趣的地方:不知大家又没有用TSession.GetDriverNames 取过系统 ODBC DRIVER 名,我用的时候 DRIVER 名最长只能取到 31 个字符,剩下的就被截掉了,不知是我编程有问题还是 DELPHI 的 BUG;
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI
列出了你的所有 ODBC DRIVER 的详细配置;
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI
列出了你的所有 SYSTEM DSN 以及它们的配置情况;
HKEY_CURRENT_USER\Software\ODBC\ODBC.INI
列出了你的所有 USER DSN 以及它们的配置情况;
知道了以上的几个主键后,你就可以在程序中实现 %SystemRoot%\system32\odbcad32.exe 的大部分功能了。
HKEY_LOCAL_MACHINE\SOFTWARE\Borland\Database Engine
下面是你的 DBE 的配置,我就不多说了,大家拿它和 BDE 用户界面一比较就明白了。
2。关于 INTERNET 编程:
HKEY_CLASSES_ROOT\htmlfile
系统对 HTMLFILE 的处理定义;
HKEY_LOCAL_MACHINE\SOFTWARE\Clients
INTERNET Option 中 INTERNET PROGRAM 的设定,尤其重要的是其中的
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail。
3。关于 WINDOWS 编程
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
每次该用户启动 WINDOWS 必定执行下面的命令(如果有,当然一般都有),
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Runonce
该用户启动 WINDOWS 必定执行下面的命令(如果有),执行完后由 WINDOWS 把命令删掉,安装软件的时候特别有用,
以上两处是针对特定用户的,在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion 下还有类似的地方,是针对所有用户的,我就不罗嗦了。
2003-11-20 12:16:38 Delphi 中注册表构件TRegistry 的应用 在Delphi3.0 及以上版本中,提供了一个构件TRegistry。在程序中可以利用它来实现对WIN95/98/NT 注册表的操作,可以很方便地在注册表中增加、修改和删除键值。这样可以在程序中完成一些特殊的功能。
---- TRegistry 常用的属性和方法有(具体作用和用法请参考Delphi 帮
助):
RootKey、CreateKey、OpenKey、CloseKey、DeleteKey、ReadXXXX、WriteXXXX
(XXXX表示数据类型如String、Integer等)
我们用到的属性和方法有:
RootKey:注册表的根键名( 如HKEY_LOCAL_MACHINE等)
OpenKey( KeyName:string; CanCreate:boolean ):
使当前键为KeyName,CanCreate 表示当指定的键不存在时是否创建,True 表示创建
SetKey( KeyName,KeyValue : string ):使键KeyName的值为KeyValue
---- 应用之一:让自己的程序随WIN95/98/NT 的启动而运行
当然,你可以在"启动"程序组中加入程序的快捷方式,但这样做好象不大明智,因为大多数程序在安装时不会这样做,而是在通过在注册表增加键值,让WIN95/98/NT 在启动时运行自己的程序。如果打开注册表,找到HKEY_LOCAL_MACHINE \Software \Microsoft\Windows \CurrentVersion \Run,就会发现这个秘密了,原来许多自动运行的程序都在这里。你也可以在这里增加一个键,让你的程序也随着 WIN95/98/NT 的启动而自己运行,成为WINDOWS 下的TSR 程序。实现方法如下:
首先,在Uses 中加上Registry 单元
然后,写下面代码。
{将程序strExeFileName置为自动启动 }
function StartUpMyProgram ( strPrompt,strExeFileName : string ) : boolean;
var
registerTemp : TRegistry;
begin
registerTemp := TRegistry.Create;
//建立一个Registry实例
with registerTemp do
begin
RootKey:=HKEY_LOCAL_MACHINE;
//设置根键值为HKEY_LOCAL_MACHINE
//找到Software\Microsoft\Windows\CurrentVersion\Run
if OpenKey('Software\Microsoft\Windows\CurrentVersion\Run',True) then
//写入自己程序的快捷方式信息
begin
WriteString( strPrompt, strExeFileName );
result := true;
end
else result := false;
//善后处理
CloseKey;
Free;
end;
end;
{调用StartUpMyProgram,
使Delphi随WINDOWS启动而自动运行 }
procedure TForm1.Button1Click(Sender: TObject);
begin
memo1.lines.add('开始');
if StartUpMyProgram('delphi','C:\Program Files\borland\delphi3\bin\delphi32.exe') then
memo1.lines.add('成功')
else
memo1.lines.add('失败')
end;
    备份部分注册表的代码Procedure ExportRegistryBranch (rootsection : Integer; regroot:String; filename:String);
implementation
Function dblBackSlash(t:string):string;
var k:longint;
begin
result:=t; {Strings are not allowed to have}
for k:=length(t) downto 1 do {single backslashes}
if result[k]='\' then insert('\',result,k);
end;
Procedure ExportRegistryBranch (rootsection : Integer; regroot:String; filename:String);
var
reg:tregistry;
f:textfile;
p:PCHAR;
Procedure ProcessBranch(root:string); {recursive sub-procedure}
var
values,
keys:tstringlist;
i,j,k:longint;
s,t:string; {longstrings are on the heap, not on the stack!}
begin
writeln(f); {write blank line}
case rootsection of
HKEY_CLASSES_ROOT : s := 'HKEY_CLASSES_ROOT';
HKEY_CURRENT_USER : s := 'HKEY_CURRENT_USER';
HKEY_LOCAL_MACHINE : s := 'HKEY_LOCAL_MACHINE';
HKEY_USERS : s := 'HKEY_USERS';
HKEY_PERFORMANCE_DATA: s := 'HKEY_PERFORMANCE_DATA';
HKEY_CURRENT_CONFIG : s := 'HKEY_CURRENT_CONFIG';
HKEY_DYN_DATA : s := 'HKEY_DYN_DATA';
end;
Writeln(f,'['+s+'\'+root+']'); {write section name in brackets}
reg.OpenKey(root,false);
values := tstringlist.create;
keys:=tstringlist.create;
reg.getvaluenames (values); {get all value names}
reg.getkeynames (keys); {get all sub-branches}
for i:=0 to values.count-1 do {write all the values first}
begin
s := values[i];
t := s; {s=value name}
if s= ''then
s:='@' {empty means "default value", write as @}
else
s:='"' + s + '"'; {else put in quotes}
write(f,dblbackslash(s)+ '=' ); {write the name of the key to the file}
Case reg.Getdatatype(t) of {What type of data is it?}
rdString,
rdExpandString: {String-type}
Writeln(f,'"' + dblbackslash(reg.readstring(t) + '"'));
rdInteger: {32-bit unsigned long integer}
Writeln(f,'dword:' + inttohex(reg.readinteger(t),8));
{ write an array of hex bytes if data is "binary." Perform a line feed after approx. 25 numbers so the line length stays within limits }
rdBinary :
begin
write(f,'hex:');
j := reg.getdatasize(t); {determine size}
getmem(p,j); {Allocate memory}
reg.ReadBinaryData(t,p^,J); {read in the data, treat as pchar}
for k:=0 to j-1 do begin
Write(f,inttohex(byte(p[k]),2)); {Write byte as hex}
if k<>j-1 then {not yet last byte?}
begin
write(f,','); {then write Comma}
if (k>0) and ((k mod 25)=0) then {line too long?}
writeln(f,'\'); {then write Backslash + lf}
end; {if}
end; {for}
freemem(p,j); {free the memory}
writeln(f); {Linefeed}
end;
ELSE
writeln(f,'""'); {write an empty string if datatype illegal/unknown}
end; {case}
end; {for}
reg.closekey;
{value names all done, no longer needed}
values.free;
{Now al values are written, we process all subkeys}
{Perform this process RECURSIVELY...}
for i := 0 to keys.count -1 do
ProcessBranch(root+'\'+keys[i]);
keys.free; {this branch is ready}
end;
begin
if regroot[length(regroot)]='\' then {No trailing backslash}
setlength(regroot,length(regroot)-1);
Assignfile(f,filename); {create a text file}
rewrite(f);
IF ioresult<>0 then
EXIT;
Writeln(f,'REGEDIT4'); {"magic key" for regedit}
reg:=tregistry.create;
try
reg.rootkey:=rootsection;
ProcessBranch(regroot); {Call the function that writes the branch and all subbranches}
finally
reg.free; {ready}
close(f);
end;
end;
end.
2003-11-20 12:22:54 读写网络上其他计算机注册表的代码procedure NetReg;
var
R: TRegistry;
S: TStringList;
begin
R:=TRegistry.Create;
S:=TStringList.Create;
WriteLn(R.RegistryConnect('\\OtherPC'));
WriteLn(R.OpenKeyReadOnly('Software'));
R.GetKeyNames(S);
WriteLn(S.CommaText);
S.Free;
R.Free;
end;
   关于查看注册表的程序unit regform;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Registry;
type
TForm1 = class(TForm)
ListSub: TListBox;
ListValues: TListBox;
ComboKey: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
ComboLast: TComboBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListSubClick(Sender: TObject);
procedure ComboKeyChange(Sender: TObject);
procedure ComboLastChange(Sender: TObject);
private
Reg: TRegistry;
public
procedure UpdateAll;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
Reg := TRegistry.Create;
Reg.OpenKey ('\', False);
UpdateAll;
// select the current root(选择当前的根目录)
ComboKey.ItemIndex := 1;
ComboLast.Items.Add('\'); ///////
ComboLast.ItemIndex := 0;
end;
//更新
procedure TForm1.UpdateAll;
begin
Caption := Reg.CurrentPath;
if Capti [Root]';
if Reg.HasSubKeys then
Reg.GetKeyNames(ListSub.Items)
else
ListSub.Clear;
Reg.GetValueNames(ListValues.Items);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Reg.CloseKey;
Reg.Free;
end;
procedure TForm1.ListSubClick(Sender: TObject);
var
NewKey, Path: string;
nItem: Integer;
begin
// get the selection(获取选择项)
NewKey := ListSub.Items [ListSub.ItemIndex];
Reg.OpenKey (NewKey, False);
// save the current path (eventually adding a \)(在不列出于列表时保存路径)
// only if the it is not already listed
Path := Reg.CurrentPath;
if Path < '\' then
Path := '\' + Path;
nItem := ComboLast.Items.IndexOf (Path);
if nItem < 0 then
begin
ComboLast.Items.Insert (0, Path);
ComboLast.ItemIndex := 0;
end
else
ComboLast.ItemIndex := nItem;
UpdateAll;
end;
procedure TForm1.ComboKeyChange(Sender: TObject);
begin
case ComboKey.ItemIndex of
0: Reg.RootKey := HKEY_CLASSES_ROOT;
1: Reg.RootKey := HKEY_CURRENT_USER;
2: Reg.RootKey := HKEY_LOCAL_MACHINE;
3: Reg.RootKey := HKEY_USERS;
4: Reg.RootKey := HKEY_CURRENT_CONFIG;
5: Reg.RootKey := HKEY_DYN_DATA;
end;
Reg.OpenKey ('\', False);
UpdateAll;
ComboLast.Items.Clear;
end;
procedure TForm1.ComboLastChange(Sender: TObject);
begin
Reg.OpenKey (ComboLast.Text, False);
UpdateAll;
end;
end.
  
     获得注册表项下的所有值Var
Reg : TRegistry;
list : TStrings;
i : Integer;
Begin
Reg:=TRegistry.Create;
Reg.RootKey:='HKEY_LOCAL_MACHINE';
If Reg.OpenKey('\Software\Microsoft\CurrentVersion\Run', false) then
Begin
List:=TStringList.Create;
Reg.GetValueNames(List);
For i:=0 to list.Count-1 do
If Reg.ValueExists(List[i]) then
Begin
Case Reg.GetDataType(List[i]) of rdInteger: Reg.ReadInteger(List[i]);
rdBinary: Reg.ReadBinaryData(List[i]);
else
Reg.ReadString(List[i]);
End;
End;
End;

////////////////读取节点值//////////////

uses Registry;
function ReadValue(mRootKey: HKEY; mKey, mName: string): string;
var
vRegDataInfo: TRegDataInfo;
begin
Result := '';
with TRegistry.Create do try
RootKey := mRootKey;
if not OpenKey(mKey, False) then Exit;
GetDataInfo(mName, vRegDataInfo);
case vRegDataInfo.RegData of
rdUnknown: Exit;
rdString, rdExpandString: Result := ReadString(mName);
rdInteger: Result := IntToStr(ReadInteger(mName));
rdBinary: begin
SetLength(Result, vRegDataInfo.DataSize);
ReadBinaryData(mName, Result[1], vRegDataInfo.DataSize);
end;
end;
finally
CloseKey;
Free;
end;
end; { ReadValue }

0 0
原创粉丝点击