首页 > 代码库 > 读写系统/用户环境变量
读写系统/用户环境变量
转自: http://delphi.cjcsoft.net/viewthread.php?tid=43647
使用 SetEnvironmentVariable 和 GetEnvironmentVariable 似乎是
只能对当前进程环境设置环境变量,所以设置后没有能在系统设置里看到,用下列
设置注册表的方法则可以全局设置系统环境变量或者用户环境变量,再发送一条系
统广播通知,达到立即生效的目的.
Reading and Writing System-Wide Environment Variables.Title: Reading and Writing System-Wide Environment Variables.Question: How do you set an environment variable that will apply outside the process that set the variable or those spawned by it?Answer:On Windows 2000, if you open the control panel and double click on the system icon, the system properties dialog box will open. On the "Advanced" tab, you can click the "Environment Variables" tab to see a list of the user and system environment variables. The procedures and functions below allow you to read and write those variables.It is worth mentioning that you can also use "GetEnvironmentVariable" and "SetEnvironmentVariable" to read and write environment variables. However, if you set and environment variable with "SetEnvironmentVariable", the value you set applies only to the process that called "SetEnvironmentVariable" or are spawned by it.The first two procedures read and write environment variables for the current user.function GetUserEnvironmentVariable(const name: string): string;var rv: DWORD;begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; OpenKey(‘Environment‘, False); result := ReadString(name); finally Free endend;procedure SetUserEnvironmentVariable(const name, value: string);var rv: DWORD;begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; OpenKey(‘Environment‘, False); WriteString(name, value); SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam (PChar(‘Environment‘)), SMTO_ABORTIFHUNG, 5000, rv); finally Free endend;The next two procedures read and write environment variables for the system and thus affect all users.function GetSystemEnvironmentVariable(const name: string): string;var rv: DWORD;begin with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; OpenKey(‘SYSTEM\CurrentControlSet\Control\Session ‘ + ‘Manager\Environment‘, False); result := ReadString(name); finally Free endend;// Modified from// http://www.delphiabc.com/TipNo.asp?ID=117// The original article did not include the space in // "Session Manager" which caused the procedure to fail.procedure SetSystemEnvironmentVariable(const name, value: string);var rv: DWORD;begin with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; OpenKey(‘SYSTEM\CurrentControlSet\Control\Session ‘ + ‘Manager\Environment‘, False); WriteString(name, value); SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam (PChar(‘Environment‘)), SMTO_ABORTIFHUNG, 5000, rv); finally Free endend;
读写系统/用户环境变量
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。