Created
April 11, 2023 08:45
-
-
Save HACKE-RC/52c50c0d928cc2e292e147f4f68d9cd5 to your computer and use it in GitHub Desktop.
Implementation of a function that can change Environment Variable in Windows (actually) by modifying Registry Keys.
This file contains 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
#inlclude <windows.h> | |
#include <stdio.h> | |
// function to set a environment variable globally by editing the registry keys. | |
NTSTATUS SetEnvironmentVariableR(LPCSTR lpName, LPCSTR lpValue){ | |
HKEY hKey; // this will hold the handle to the registry key. | |
// We are going to open the registry key for HKEY_CURRENT_USER\Environment. | |
RegCreateKey(HKEY_CURRENT_USER, "Environment", &hKey); | |
// Error check. | |
if (hKey == NULL) { | |
printf("RegCreateKey failed\n"); | |
printf("Error code: %d", GetLastError()); | |
return STATUS_UNSUCCESSFUL; | |
} | |
// Now we are going to set the value of the environment variable. | |
RegSetValueEx(hKey, lpName, 0, REG_SZ, lpValue, lstrlen(lpValue)+1); | |
// Checking if the operation was successful by checking if the registry key actually exists. | |
if (!RegGetValueA(hKey, "Environment", lpValue, RRF_RT_REG_SZ, NULL, NULL, NULL)){ | |
printf("RegSetValueEx unsuccessful!"); | |
printf("Error code: %d", GetLastError()); | |
return STATUS_UNSUCCESSFUL; | |
} | |
return STATUS_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment