首页 > 代码库 > java设置环境变量小工具
java设置环境变量小工具
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Registry; type TfrmMain = class(TForm) btn1: TButton; edt1: TEdit; lbl1: TLabel; procedure btn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; function ExpandEnvironment(const strValue: string): string; function SetGlobalEnvironment(const envName, envValue: string; const isUser: Boolean = True): Boolean; implementation {$R *.dfm} procedure TfrmMain.btn1Click(Sender: TObject); var path:string; begin SetGlobalEnvironment(‘JAVA_HOME‘,edt1.Text); SetGlobalEnvironment(‘CLASSPATH‘,‘.;%JAVA_HOME%/jre/lib/rt.jar;%JAVA_HOME%/lib/tools.jar;%JAVA_HOME%/lib;‘); path := ExpandEnvironment(‘%PATH%‘); path := path + ‘;%JAVA_HOME%/bin‘; SetGlobalEnvironment(‘PATH‘,path); end; /// <summary> /// 设置系统级环境变量参数函数 /// </summary> /// <param name="envName">环境变量名</param> /// <param name="envValue">环境变量值</param> /// <param name="isUser">为true表示只更新当前操作员的环境变量</param> /// <returns></returns> function SetGlobalEnvironment(const envName, envValue: string; const isUser: Boolean = True): Boolean; resourcestring REG_MLOCATION =‘System/CurrentControlSet/Control/Session Manager/Environment‘; // 环境变量存储在注册表中的位置 REG_ULOCATION = ‘Environment‘; begin with TRegistry.Create do try if isUser then // 设置当前用户的环境变量 Result := OpenKey(REG_ULOCATION, True) else // 设置系统环境变量,对所有用户有效 begin RootKey := HKEY_LOCAL_MACHINE; Result := OpenKey(REG_MLOCATION, True); end; if Result then begin WriteString(envName, envValue); // 设置注册表中环境变量的值 SetEnvironmentVariable(PChar(envName), PChar(envValue)); // 更新当前进程的环境变量值 SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar(‘Environment‘))); // 发送消息通知所有上层的窗口,环境参数发生变化 end; finally Free; end; end; /// <summary> /// 获取环境变量 /// </summary> /// <param name="strValue">环境变量名</param> /// <returns>环境变量值</returns> function ExpandEnvironment(const strValue: string): string; var chrResult: array[0..1023] of Char; wrdReturn: DWORD; begin wrdReturn := ExpandEnvironmentStrings(PChar(strValue), chrResult, 1024); if wrdReturn = 0 then Result := strValue else begin Result := Trim(chrResult); end; end; end.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。