编程(delphi)设置环境变量

 

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值