Search code examples
c#setup-projectstartupregistry

Visual Studio Setup Project and placing application in startup path


I've created a function that executes in the beginning of an installation to create a registry key in the SOFTWARE\Microsoft\Windows\CurrentVersion\Run path, so the app can start when the computer starts.

The function works in a XP / 2003 machine but not on Windows 7. The install application Elevates the privileges during installation automatically because it is installing a windows service program. So I'm wondering what am I doing wrong again?

Here is the function:

private void RegisterInStartup(bool isChecked)
{
    try
    {
        string t_registeryPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

        RegistryKey registryKey =
            Registry.LocalMachine.OpenSubKey(t_registeryPath, true);

        if (registryKey == null)
            registryKey = Registry.LocalMachine.CreateSubKey(t_registeryPath);

        if (isChecked)
        {
            string tgt_dir = Context.Parameters["targetPath"];
            if (!Directory.Exists(tgt_dir))
                return;

            string t_exeName = Path.Combine(tgt_dir, "AppTaskbarNotificator.exe");
            if (!File.Exists(t_exeName))
                return;

            registryKey.SetValue("AppTaskbar", t_exeName);
        }
        else
        {
            registryKey.DeleteValue("AppTaskbar");
        }
    }
    catch (Exception)
    {
        return;
    }
}

and it is placed in the Install function which is overridden in the Installer Class of the App in mind.

public override void Install(IDictionary stateSaver)
{
    base.Install(stateSaver);
    System.Diagnostics.Debugger.Break();

    RegisterInStartup(true);
    StartApp();
}

Thanks in advance.


Solution

  • HKEY_LOCAL_MACHINE is a per-machine location, so your custom action needs Administrator privileges to write in it. You can give it these privileges by making it deferred with no impersonation.

    Visual Studio 2010 makes custom actions deferred with no impersonation by default, but older versions don't. So you may have to edit the MSI with Orca to set the appropriate flags.

    Another solution is to write your registry entry in HKEY_CURRENT_USER.