Search code examples
c#wpfwindowssetup-project

How can I clean up a 'Run on Startup' registry key in a Windows setup project?


I've written a WPF application with an accompanying Windows setup project. The application has an option to 'Run on startup', at which point a key is added to the SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry. The setup project doesn't create this key by default because the option is disabled by default; however, I want to make sure if someone uninstalls the application the registry key will be removed.

Is this possible? Also, what is the behavior if the key isn't removed? I've assumed Windows will try to run the application and nothing will happen but I have yet to test this situation.

Edit - As requested, the registry key is set up from code as follows:

using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
  if (key != null)
  {
    key.SetValue("MyApp", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
  }
}

It is done this way because by default, I don't want the app to run on startup; thus, the registry key shouldn't be created until the user opts to use that setting.


Solution

  • If you created that key data with an install custom action, then you'll need to create an uninstall custom action to remove it. Strictly speaking you should also include a rollback custom action to remove it in case your install fails and rolls back.

    An MSI file is a database of changes to the system - that's why anything in there can be uninstalled, but it doesn't keep track of changes you make with your code.

    I'd be tempted to make this an option somewhere in the application cofiguration, not the install, so the app could have an option "start at logon time" that the user could turn on and off. Currently anyone that wants to change that setting has to fiddle with the registry or re-install the app, depending on how smart they might be about this stuff.

    With other install tools you get more choices. For example, Visual Studio doesn't do multiple features. With another tool (such as WiX) you could create a feature that the user checks if the Start is required, and that feature contains the component that creates the registry key using Windows Installer registry entries instead of code. Apart from there being no coding, the entry gets removed at uninstall time; the user can go into maintenance mode and uninstall (or add) the feature at any time; install failure will clean it up automatically. And that's just one way of providing the functionality.

    Visual Studio setups are relatively easy to use because they expose only a limited set of Windows Installer features, so you get some simplicity but you pay for it if you want to go beyond the capabilities that VS setups provide. But you also get involved more deeply in Windows Installer.