SoFunction
Updated on 2025-03-06

Summary of two common methods for realizing automatic software startup in C#

Method 1: Create the software shortcut to the computer's automatic startup directory (no administrator permission is required)

1. Necessary citations

using System;
using ;
using ;
using ;
using ;
using IWshRuntimeLibrary;  //Add a reference and search for Windows Script Host Object Model in Comusing ;

2. Code implementation - just call SetMeAutoStart(bool onOff) method, the parameter onOff indicates the self-start switch

/// <summary>
        /// Shortcut name - any custom        /// </summary>
        private const string QuickName = "TCNVMClient";
        /// <summary>
        /// Automatically obtain the automatic system startup directory        /// </summary>
        private string systemStartPath { get { return (); } }
        /// <summary>
        /// Automatically obtain the complete path of the program        /// </summary>
        private string appAllPath { get { return ().; } }
        /// <summary>
        /// Automatically get desktop directory        /// </summary>
        private string desktopPath { get { return (); } }
        /// <summary>
        /// Set automatic startup - just call the method to change the method. The bool variable in the parameter controls the switch that starts the startup, and the default is to enable the self-start startup        /// </summary>
        /// <param name="onOff">Self-Open switch</param>        public void SetMeAutoStart(bool onOff = true)
        {
            if (onOff)//Start            {
                //Get the path collection of startup path application shortcuts                List&lt;string&gt; shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //There are 2 shortcuts, keep one shortcut - avoid more duplication than                if ( &gt;= 2)
                {
                    for (int i = 1; i &lt; ; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
                else if ( &lt; 1)//Create a shortcut if it does not exist                {
                    CreateShortcut(systemStartPath, QuickName, appAllPath, "Zhongji vending machine");
                }
            }
            else//The power is not started            {
                //Get the path collection of startup path application shortcuts                List&lt;string&gt; shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //If there is a shortcut, iterate and delete it all                if ( &gt; 0)
                {
                    for (int i = 0; i &lt; ; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
            }
            //Create desktop shortcuts - Cancel comment if needed            //CreateDesktopQuick(desktopPath, QuickName, appAllPath);
        }
        /// &lt;summary&gt;
        /// Create a shortcut to the target path to create a specified file        /// &lt;/summary&gt;
        /// <param name="directory">Target Directory</param>        /// <param name="shortcutName">Shortcut Name</param>        /// <param name="targetPath">File full path</param>        /// <param name="description">Description</param>        /// <param name="iconLocation">Icon Address</param>        /// <returns>Success or failure</returns>        private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
        {
            try
            {
                if (!(directory)) (directory);                         //Create if the directory does not exist                //Add a reference Search in Com Windows Script Host Object Model                string shortcutPath = (directory, ("{0}.lnk", shortcutName));          //Composition path                WshShell shell = new ();
                IWshShortcut shortcut = ()(shortcutPath);    //Create a shortcut object                 = targetPath;                                                               //Specify the target path                 = (targetPath);                                  //Set the starting position                 = 1;                                                                       //Set the operation mode, default to the regular window                 = description;                                                             //Setting Notes                 = (iconLocation) ? targetPath : iconLocation;    //Set icon path                ();                                                                                //Save shortcut                return true;
            }
            catch(Exception ex)
            {
                string temp = ;
                temp = "";
            }
            return false;
        }
        /// &lt;summary&gt;
        /// Get the shortcut path collection of specified applications under the specified folder        /// &lt;/summary&gt;
        /// <param name="directory">Folder</param>        /// <param name="targetPath">Target application path</param>        /// <returns> Shortcuts for target application</returns>        private List&lt;string&gt; GetQuickFromFolder(string directory, string targetPath)
        {
            List&lt;string&gt; tempStrs = new List&lt;string&gt;();
            ();
            string tempStr = null;
            string[] files = (directory, "*.lnk");
            if (files == null ||  &lt; 1)
            {
                return tempStrs;
            }
            for (int i = 0; i &lt; ; i++)
            {
                //files[i] = ("{0}\\{1}", directory, files[i]);
                tempStr = GetAppPathFromQuick(files[i]);
                if (tempStr == targetPath)
                {
                    (files[i]);
                }
            }
            return tempStrs;
        }
        /// &lt;summary&gt;
        /// Get the target file path of the shortcut - used to determine whether the automatic startup has been enabled        /// &lt;/summary&gt;
        /// &lt;param name="shortcutPath"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private string GetAppPathFromQuick(string shortcutPath)
        {
            //Path of shortcut file = @"d:\";            if ((shortcutPath))
            {
                WshShell shell = new WshShell();
                IWshShortcut shortct = (IWshShortcut)(shortcutPath);
                //The path pointed to by the shortcut file.Text = Current shortcut file IWshShortcut class.TargetPath;                //The target directory pointed to by the shortcut file.Text = Current shortcut file IWshShortcut class.WorkingDirectory;                return ;
            }
            else
            {
                return "";
            }
        }
        /// &lt;summary&gt;
        /// Delete file by path - a shortcut to delete programs from the computer's self-start directory when self-start is cancelled        /// &lt;/summary&gt;
        /// <param name="path">path</param>        private void DeleteFile(string path)
        {
            FileAttributes attr = . (path);
            if (attr == )
            {
                (path, true);
            }
            else
            {
                (path);
            }
        }
        /// &lt;summary&gt;
        /// Create shortcuts on the desktop - call if needed        /// &lt;/summary&gt;
        /// <param name="desktopPath">Desktop Address</param>        /// <param name="appPath">Application Path</param>        public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
        {
            List&lt;string&gt; shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
            //Create if not            if ( &lt; 1)
            {
                CreateShortcut(desktopPath, quickName, appPath, "Software Description");
            }
        }

Method 2: How to modify the computer registry (requires administrator permissions)

1. Necessary citations

using Microsoft.Win32;
using System;
using ;
using ;

2. Code implementation - just call SetMeStart(bool onOff) method, the parameter onOff indicates the self-start switch

/// &lt;summary&gt;
        /// Set this program to enable self-start        /// &lt;/summary&gt;
        /// <param name="onOff">Self-Open switch</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public static bool SetMeStart(bool onOff)
        {
            bool isOk = false;
            string appName = ().;
            string appPath = ().;
            isOk = SetAutoStart(onOff, appName, appPath);
            return isOk;
        }
        /// &lt;summary&gt;
        /// Set the application to or not to boot        /// &lt;/summary&gt;
        /// <param name="onOff">Self-Open switch</param>        /// <param name="appName">Application name</param>        /// <param name="appPath">Application full path</param>        public static bool SetAutoStart(bool onOff, string appName, string appPath)
        {
            bool isOk = true;
            //If you have not set to boot to set to boot            if (!IsExistKey(appName) &amp;&amp; onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            //If setting from setting to power on boot to not setting to power on boot            else if (IsExistKey(appName) &amp;&amp; !onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            return isOk;
        }
        /// &lt;summary&gt;
        /// Determine whether the registered key-value pair exists, that is, whether it is in the boot state        /// &lt;/summary&gt;
        /// <param name="keyName">key value name</param>        /// &lt;returns&gt;&lt;/returns&gt;
        private static bool IsExistKey(string keyName)
        {
            try
            {
                bool _exist = false;
                RegistryKey local = ;
                RegistryKey runs = (@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runs == null)
                {
                    RegistryKey key2 = ("SOFTWARE");
                    RegistryKey key3 = ("Microsoft");
                    RegistryKey key4 = ("Windows");
                    RegistryKey key5 = ("CurrentVersion");
                    RegistryKey key6 = ("Run");
                    runs = key6;
                }
                string[] runsName = ();
                foreach (string strName in runsName)
                {
                    if (() == ())
                    {
                        _exist = true;
                        return _exist;
                    }
                }
                return _exist;
            }
            catch
            {
                return false;
            }
        }
        /// &lt;summary&gt;
        /// Write or delete the registry key-value pair, that is, set to start or not start on the computer        /// &lt;/summary&gt;
        /// <param name="isStart">Whether to start the computer</param>        /// <param name="exeName">Application name</param>        /// <param name="path">Application path with program name</param>        /// &lt;returns&gt;&lt;/returns&gt;
        private static bool SelfRunning(bool isStart, string exeName, string path)
        {
            try
            {
                RegistryKey local = ;
                RegistryKey key = (@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (key == null)
                {
                    ("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");
                }
                //If the power starts automatically, add key-value pairs                if (isStart)
                {
                    (exeName, path);
                    ();
                }
                else//Otherwise, delete the key value pair                {
                    string[] keyNames = ();
                    foreach (string keyName in keyNames)
                    {
                        if (() == ())
                        {
                            (exeName);
                            ();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string ss = ;
                return false;
                //throw;
            }
            return true;
        }

This is the article about the two common methods of starting up C# software. This is all about this article. For more related content on starting up C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!