unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,StdCtrls,registry;//别忘了引用这个,否则可操作不了注册表
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
CheckBox1: TCheckBox;
procedure ComboBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
isUserVar:Boolean=false;
implementation
{$R *.dfm}
function SetGlobalEnvironment(const Name, Value: string;
User: Boolean): Boolean;
resourcestring //本代码在xp下使用,其他版本的操作系统可能因为注册表结构的不同而不能通用
REG_MACHINE_LOCATION = 'SYSTEM/ControlSet001/Control/Session Manager/Environment'; //系统环境变量所在节点路径
REG_USER_LOCATION = 'Environment';//当前用户变量所在路径
begin
with TRegistry.Create do
try
if User then { 设置用户环境变量 }
Result := OpenKey(REG_USER_LOCATION, True)
else { 设置系统环境变量 }
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := OpenKey(REG_MACHINE_LOCATION, True);
end;
if Result then
begin
WriteString(Name, Value); { 写入注册表 }
{ 更新当前环境变量进程 }
SetEnvironmentVariable(PChar(Name), PChar(Value));
{ 发送消息到所有活动窗口并更新 }
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
end;
finally
Free;
end;
end; { 设置完毕 }
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
ComboBox2.ItemIndex:=ComboBox1.ItemIndex;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ComboBox1.ItemIndex:=0;
ComboBox2.ItemIndex:=0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var name,value:String;
begin
name:=ComboBox1.Text;
value:=ComboBox2.Text;
SetGlobalEnvironment(name,value,isUserVar);
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if(CheckBox1.Checked)
then
begin
CheckBox1.Caption:='当前为设置用户变量';
isUserVar:=true;
end
else
begin
CheckBox1.Caption:='当前为设置系统变量';
isUserVar:=false;
end
end;
end.