Adding Application Directory to PATH variable in Visual Studio Setup Projects

To add the directory where a program is installed to the PATH environment variable requires a Custom Action in your Visual Studio Setup project.

Create a library (.dll), follow the instructions in this article and paste the C# code into a class. (VB.Net version is here)

This code adds the program’s directory to the PATH variable stored in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

However, to notify the system that the PATH variable has changed, a broadcast message needs to be sent to all windows using the Windows function SendMessageTimeout. This function can be declared using the DllImport attribute:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SendMessageTimeout(
  IntPtr hWnd,
  int Msg,
  int wParam,
  string lParam,
  int fuFlags,
  int uTimeout,
  out int lpdwResult

public const int HWND_BROADCAST = 0xffff;
public const int WM_SETTINGCHANGE = 0x001A;
public const int SMTO_NORMAL = 0x0000;
public const int SMTO_BLOCK = 0x0001;
public const int SMTO_ABORTIFHUNG = 0x0002;
public const int SMTO_NOTIMEOUTIFNOTHUNG = 0x0008

Call this function from a .Net method passing the correct parameters after manipulating the registry:

static void BroadcastEnvironment()
  int result;
  SendMessageTimeout((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",

After running the installer, open the cmd prompt, and type PATH. You will find your directory added to the system path.

Other possibilities to implement this functionality are to edit the created .msi file, or to add the registry key of the Environment variable to the setup project. However, this seems to be a destructive method during uninstall.

One Response to Adding Application Directory to PATH variable in Visual Studio Setup Projects

  1. JJ says:

    Works for me at installation. Not at uninstallation. Weird.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: