ahmd0
ahmd0

Reputation: 17293

Access custom environment variable without rebooting (using C++)

I'm writing a program using C++ that takes advantage of a custom system-wide environment variable. That variable is set by an msi installer. Later my program reads it using GetEnvironmentVariable() API.

The problem is that it seems like the system needs to be rebooted for my custom environment variable to be visible in my program and I'd hate to reboot the system just for that.

What seems to be odd is that if (without rebooting) I right-click on My Computer and then go into Properties -> Advanced and click on "Environment variables" my custom environment variable is in that list but for some reason GetEnvironmentVariable() still doesn't see it.

So is there any other API that I can use that will work without rebooting the system? (As system properties can clearly see it then.)

Upvotes: 4

Views: 657

Answers (2)

mickeymicks
mickeymicks

Reputation: 679

i recently encountered something like this and broadcasting the message is the correct way as explained in this kb (and by parapura):

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

however, i would suggest to put _T() around the "Environment" (or maybe an 'L') to make sure you are passing in the correct string (ansi or wide). like this:

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

i used the above in a commandline app. without the _T() the message sending succeeds but my system never seem to receive update of the environment variable.

btw, the 'setx' command line probably uses the same mechanism to update the environment variables. also, i'm using this in an atl dll.

Upvotes: 1

parapura rajkumar
parapura rajkumar

Reputation: 24403

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

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

Explorer handles this message correctly so programs started after this broadcast will see the changes.

  1. Also technically you don't need to reboot , a simple logoff and login will suffice
  2. Another option is to simply restart explorer

Upvotes: 3

Related Questions