[Windows] Launch Winform On Start - The Easy Method



Basically all we're doing is creating a shortcut to our app in the Windows Start-Up folder.

Add a reference to Windows Script Host Object Model



Call this method in your code... (I like to do it in the form closing event myself)

void LaunchOnStartup()
{
    // On Windows Startup
    string shortcutLocation = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\MyApp.lnk";

    if (!File.Exists(shortcutLocation))
    {
        try
        {
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();

            System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();

            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutLocation);
            shortcut.Description = "My App";
            shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            shortcut.TargetPath = curAssembly.Location;
           
            shortcut.Save();
        }
        catch (Exception ex)
        {
        }
    }
}

Comments