Skip to content

Instantly share code, notes, and snippets.

@HACKE-RC
Created April 11, 2023 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HACKE-RC/52c50c0d928cc2e292e147f4f68d9cd5 to your computer and use it in GitHub Desktop.
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.
#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