As suggested by Joel, the correct solution is to install the shortcut in the program files folder during installation, and then copy the .lnk file to the startup folder. Trying to create a shortcut is harder.
The code below does the following:
- It gets the path to the startup folder of all users. Environment.GetSpecialFolder is quite limited and does not have a link to this folder, and as a result you need to make a system call.
- There are methods for copying and deleting a shortcut.
Ultimately, I also wanted to make sure it was elegantly crafted on Vista, if the user running the application was a regular user, they were asked to enter their credentials. I created a post here on this subject, so check it out here if it matters to you. How to copy a file as a "Standard user"? in Vista (that is, an “administrative choice application”), asking the user for administrator credentials?
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Principal; using System.Windows.Forms; using System.Runtime.InteropServices; namespace BR.Util { public class StartupLinkUtil { [DllImport("shell32.dll")] static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate); public static string getAllUsersStartupFolder() { StringBuilder path = new StringBuilder(200); SHGetSpecialFolderPath(IntPtr.Zero, path, CSIDL_COMMON_STARTUP, false); return path.ToString(); } private static string getStartupShortcutFilename() { return Path.Combine(getAllUsersStartupFolder(), Application.ProductName) + ".lnk"; } public static bool CopyShortcutToAllUsersStartupFolder(string pShortcutName) { bool retVal = false; FileInfo shortcutFile = new FileInfo(pShortcutName); FileInfo destination = new FileInfo(getStartupShortcutFilename()); if (destination.Exists) {
While I was writing this solution, I was thinking about how to better deal with a problem that would not require users to escalate sensitive data in order to disable startup at startup. My solution was to check as soon as the program loads, if the user coverage parameter is called RunOnStartup. To determine if the application was launched when loading or logging in, I added an argument to the shortcut, which is added to the "All Users → Startup" folder with the shortcut.
// Quit the application if the per user setting for RunOnStartup is false. if (args != null && args.Length > 0 && args[0].Contains("startup")) { if (Settings1.Default.RunOnStartup == false) { Application.Exit(); } }
blak3r
source share