0

I want to add my application to Windows startup programatically. I am using the below code. But when I shut down and start Windows again then my application doesn't start.

public static void AddApplicationToStartup()
   {
     using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
      {
        key.SetValue("My Program", "\"" + Application.ExecutablePath + "\"");
      }
   }
2

1 Answer 1

2

You are omitting an essential detail in your question. But that isn't essential to answer the question, this code can never work. In order to write this registry key, your program must run with UAC elevation. Done by using requireAdministrator in the application manifest. If it is missing then OpenSubKey() is going to throw an exception and the value is never written. Easy to see of course.

If it does not fail then you'll write the value just fine, but the program will never start at startup. Windows does not permit programs to ask for UAC elevation at startup, it simply refuses to start them. It is a core security problem, the user has no idea where the UAC elevation prompt came from and cannot reliably give consent.

You always need a second program to do this correctly. Two basic scenarios:

  • Your main program doesn't run elevated, it starts the helper program and it asks for UAC elevation so it can write the registry. No problem starting your main program with the registry key now. You probably saw programs before that have a button with the "shield" icon.
  • Your main program always runs elevated, your registry key must start a helper program that does not ask for UAC elevation. Which does little but provide a button to start the main program. The UAC consent dialog is now displayed immediately after the user clicks the button, Windows doesn't object to that since the user clearly knows what is happening. If your machine is cursed with Adobe software then you know what that looks like.

The first bullet covers the way everybody does this: write the key with an installer. Always a separate program, always runs elevated.

1
  • Your answer is great but would you like to give me source code, i am really in need of it. It will be great, if you could further help me.Thanks Apr 13, 2015 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.