Access to user environment variable without rebooting (using C ++)

I am writing a program using C ++ that uses a user-defined system-wide environment variable. This variable is set by the msi installer. Later, my program reads it using the GetEnvironmentVariable () API.

The problem is that it seems like it is necessary to reboot the system so that my user environment variable is visible in my program, and I would not want to reboot the system just for this.

It seems strange that if (without rebooting), I right-click on "My Computer" and then go to "Properties" β†’ "Advanced" and click on "Environment Variables". My environment variable is on this list, but for some reason GetEnvironmentVariable () still does not see it.

So, is there any other API that I can use that will work without rebooting the system? (Since system properties can clearly see this.)

+4
source share
2 answers

If you want to do this without rebooting the system, you need to transfer it . Something along the lines

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue); 

Explorer handles this message correctly, so programs launched after this translation will see the changes.

  • Also, technically, you do not need to reboot, just exit and login will be sufficient
  • Another option is to simply restart Explorer
+3
source

I recently came across something similar, and broadcasting the message is the correct way, as described in this kb (and parapura):

http://support.microsoft.com/kb/104011

however, I would suggest putting _T () around the "environment" (or possibly "L") to make sure you are passing in the correct line (ansi or wide). eg:

  SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) _T("Environment"), SMTO_ABORTIFHUNG, 5000, &dwReturnValue); 

I used the above in a command line application. without _T (), sending the message is successful, but my system never receives updates to the environment variable.

btw, the 'setx' command line probably uses the same mechanism to update environment variables. In addition, I use this in the atl dll.

+1
source

Source: https://habr.com/ru/post/1390362/


All Articles