Created
November 23, 2022 13:17
-
-
Save jarroddavis68/11166c49d75e5e93c22567f7c735e099 to your computer and use it in GitHub Desktop.
SetGlobalEnvironment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function SetGlobalEnvironment(const aName: string; const aValue: string; const aUser: Boolean = True): Boolean; | |
const | |
REG_MACHINE_LOCATION = 'System\CurrentControlSet\Control\Session Manager\Environment'; | |
REG_USER_LOCATION = 'Environment'; | |
var | |
lParam, wParam: NativeInt; | |
Buf: Array[0..11] of Char; | |
dwReturnValue: DWORD_PTR; | |
begin | |
Buf := 'Environment'+#0; | |
wParam := 0; | |
{This gives us a pointer to the Buffer for Windows to read.} | |
lParam := NativeInt(@Buf[0]); | |
with TRegistry.Create do | |
try | |
LazyWrite := false; | |
if aUser then | |
begin | |
{ User Environment Variable } | |
RootKey := HKEY_CURRENT_USER; | |
Result := OpenKey(REG_USER_LOCATION, True); | |
end else | |
begin | |
{ System Environment Variable } | |
RootKey := HKEY_LOCAL_MACHINE; | |
Result := OpenKey(REG_MACHINE_LOCATION, True); | |
end; | |
if not Result then Exit; | |
WriteString(aName, aValue); { Write Registry for Global Environment } | |
finally | |
Free; | |
end; | |
{ Update Current Process Environment Variable } | |
SetEnvironmentVariable(PChar(aName), PChar(aValue)); | |
{ Send Message To All Top Windows for Refresh } | |
//SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LPARAM(PChar('Environment'))); | |
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, wParam, lParam, SMTO_ABORTIFHUNG, 5000, @dwReturnValue); | |
end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment