Unome
Unome

Reputation: 6900

Set an Environment Variable Programatically in the Machine Scope and send SettingsChange Message

I've got some code that sets environment variables in MACHINE, USER and PROCESS scope.

User and Process are performing as expected, but for some reason when I try to verify the machine scoped variable, its not being found.

My code to set the environment variables is pretty simple:

Environment.SetEnvironmentVariable("foo1", "bar1", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("foo2", "bar2",   EnvironmentVariableTarget.User);
Environment.SetEnvironmentVariable("foo3", "bar3", EnvironmentVariableTarget.Process);

Am I missing something?

UPDATE

I'm trying to solve the problem using what was stated with sending a WM_SETTINGCHANGE message. I'm curious as to whether adding in this will allow SetEnvironmentVariable to work, or if the only way to do this is through the registry.

I'm going to try both and see which works, and so far I'm hung up on broadcasting the message. From what I can tell this is the syntax needed to broadcast the message

IntPtr HWND_BROADCAST = new IntPtr(0xFFFF);
const int WM_SETTINGCHANGE = 0x001A;
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, null, "Environment");

To do this I'm using the following dll import.

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, String lParam);

Upvotes: 2

Views: 1332

Answers (1)

Alex Netkachov
Alex Netkachov

Reputation: 13552

Setting machine-level environment variable is a bit tricky. The problem is that does not immediate effect on the processes as they already running within their own environment. See more there: https://serverfault.com/questions/8855/how-do-you-add-a-windows-environment-variable-without-rebooting I'm not sure that Environment.SetEnvironmentVariable will do it for you.

Upvotes: 1

Related Questions