Two common methods of C program to realize automatic startup of software

C ා / WPF / WinForm /. Net program code realization software program starts automatically two commonly used method function examples and examples with detailed notes

Method 1: create the shortcut of the software to the automatic startup directory of the computer (without administrator permission)

1. Necessary references

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using IWshRuntimeLibrary;
using System.Diagnostics;

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

        /// <summary>
        /// Shortcut name-Any customization
        /// </summary>
        private const string QuickName = "TCNVMClient";
 
        /// <summary>
        /// Auto get system auto start directory
        /// </summary>
        private string systemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }
 
        /// <summary>
        /// Get program full path automatically
        /// </summary>
        private string appAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }
 
        /// <summary>
        /// Get desktop directory automatically
        /// </summary>
        private string desktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }
 
        /// <summary>
        /// Set automatic startup-You only need to call the method to change the bool The variable is used to control the start-up switch. The default is to start the auto start
        /// </summary>
        /// <param name="onOff">Self starting switch</param>
        public void SetMeAutoStart(bool onOff = true)
        {
            if (onOff)//Boot up
            {
                //Get the path collection for the launch path application shortcut
                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //There are 2 shortcuts, keep one shortcut-Avoid repetition
                if (shortcutPaths.Count >= 2)
                {
                    for (int i = 1; i < shortcutPaths.Count; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
                else if (shortcutPaths.Count < 1)//Create shortcut if it doesn't exist
                {
                    CreateShortcut(systemStartPath, QuickName, appAllPath, "China Kyrgyzstan cargo plane");
                }
            }
            else//Power on does not start
            {
                //Get the path collection for the launch path application shortcut
                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //If there is shortcut, traverse and delete all
                if (shortcutPaths.Count > 0)
                {
                    for (int i = 0; i < shortcutPaths.Count; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
            }
            //Create a desktop shortcut-Uncomment if necessary
            //CreateDesktopQuick(desktopPath, QuickName, appAllPath);
        }
 
        /// <summary>
        ///  Create a shortcut to the specified file to the target path
        /// </summary>
        /// <param name="directory">Target directory</param>
        /// <param name="shortcutName">Shortcut name</param>
        /// <param name="targetPath">File full path</param>
        /// <param name="description">describe</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.Exists(directory)) Directory.CreateDirectory(directory);                         //Create if directory does not exist
                //Add reference Com Mid search Windows Script Host Object Model
                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));          //Synthesis path
                WshShell shell = new IWshRuntimeLibrary.WshShell();
                IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);    //Create shortcut object
                shortcut.TargetPath = targetPath;                                                               //Specify target path
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);                                  //Set start position
                shortcut.WindowStyle = 1;                                                                       //Set the operation mode, the default is the general window
                shortcut.Description = description;                                                             //Set remarks
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;    //Set icon path
                shortcut.Save();                                                                                //Save shortcut
                return true;
            }
            catch(Exception ex)
            {
                string temp = ex.Message;
                temp = "";
            }
            return false;
        }
 
        /// <summary>
        /// Gets the collection of shortcut paths for the specified application under the specified folder
        /// </summary>
        /// <param name="directory">Folder</param>
        /// <param name="targetPath">Target application path</param>
        /// <returns>Shortcuts to the target application</returns>
        private List<string> GetQuickFromFolder(string directory, string targetPath)
        {
            List<string> tempStrs = new List<string>();
            tempStrs.Clear();
            string tempStr = null;
            string[] files = Directory.GetFiles(directory, "*.lnk");
            if (files == null || files.Length < 1)
            {
                return tempStrs;
            }
            for (int i = 0; i < files.Length; i++)
            {
                //files[i] = string.Format("{0}\\{1}", directory, files[i]);
                tempStr = GetAppPathFromQuick(files[i]);
                if (tempStr == targetPath)
                {
                    tempStrs.Add(files[i]);
                }
            }
            return tempStrs;
        }
 
        /// <summary>
        /// Get the target file path of the shortcut-Used to determine whether automatic start has been turned on
        /// </summary>
        /// <param name="shortcutPath"></param>
        /// <returns></returns>
        private string GetAppPathFromQuick(string shortcutPath)
        {
            //Path to shortcut file = @"d:\Test.lnk";
            if (System.IO.File.Exists(shortcutPath))
            {
                WshShell shell = new WshShell();
                IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
                //Path to shortcut file.Text = Current shortcut file IWshShortcut class.TargetPath;
                //Target directory to which the shortcut file points.Text = Current shortcut file IWshShortcut class.WorkingDirectory;
                return shortct.TargetPath;
            }
            else
            {
                return "";
            }
        }
 
        /// <summary>
        /// Delete files by path-Shortcut for removing programs from the computer's bootstrap directory when bootstrapping is cancelled
        /// </summary>
        /// <param name="path">Route</param>
        private void DeleteFile(string path)
        {
            FileAttributes attr = System.IO. File.GetAttributes(path);
            if (attr == FileAttributes.Directory)
            {
                Directory.Delete(path, true);
            }
            else
            {
                System.IO.File.Delete(path);
            }
        }
 
        /// <summary>
        /// Create shortcuts on the desktop-Call if necessary
        /// </summary>
        /// <param name="desktopPath">Desktop address</param>
        /// <param name="appPath">Application path</param>
        public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
        {
            List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
            //If not, create
            if (shortcutPaths.Count < 1)
            {
                CreateShortcut(desktopPath, quickName, appPath, "Software description");
            }
        }

Method 2: modify the way of computer registry (need administrator permission)

using Microsoft.Win32;
using System;
using System.Windows.Forms;
using System.Diagnostics;

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

/// <summary>
        /// Set the program to start automatically
        /// </summary>
        /// <param name="onOff">Self starting switch</param>
        /// <returns></returns>
        public static bool SetMeStart(bool onOff)
        {
            bool isOk = false;
            string appName = Process.GetCurrentProcess().MainModule.ModuleName;
            string appPath = Process.GetCurrentProcess().MainModule.FileName;
            isOk = SetAutoStart(onOff, appName, appPath);
            return isOk;
        }
 
        /// <summary>
        /// Set application to or not to boot
        /// </summary>
        /// <param name="onOff">Self starting 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 it is not set as startup setting to startup setting
            if (!IsExistKey(appName) && onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            //If the setting is from set to startup to not set to startup
            else if (IsExistKey(appName) && !onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            return isOk;
        }
 
        /// <summary>
        /// Judge whether the registration key value pair exists, i.e. whether it is in startup state
        /// </summary>
        /// <param name="keyName">Key value name</param>
        /// <returns></returns>
        private static bool IsExistKey(string keyName)
        {
            try
            {
                bool _exist = false;
                RegistryKey local = Registry.LocalMachine;
                RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runs == null)
                {
                    RegistryKey key2 = local.CreateSubKey("SOFTWARE");
                    RegistryKey key3 = key2.CreateSubKey("Microsoft");
                    RegistryKey key4 = key3.CreateSubKey("Windows");
                    RegistryKey key5 = key4.CreateSubKey("CurrentVersion");
                    RegistryKey key6 = key5.CreateSubKey("Run");
                    runs = key6;
                }
                string[] runsName = runs.GetValueNames();
                foreach (string strName in runsName)
                {
                    if (strName.ToUpper() == keyName.ToUpper())
                    {
                        _exist = true;
                        return _exist;
                    }
                }
                return _exist;
 
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// Write or delete registry key pair,That is, it is set to start or not start
        /// </summary>
        /// <param name="isStart">Start up or not</param>
        /// <param name="exeName">application name</param>
        /// <param name="path">Application path with program name</param>
        /// <returns></returns>
        private static bool SelfRunning(bool isStart, string exeName, string path)
        {
            try
            {
                RegistryKey local = Registry.LocalMachine;
                RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (key == null)
                {
                    local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");
                }
                //Add key value pair if starting from
                if (isStart)
                {
                    key.SetValue(exeName, path);
                    key.Close();
                }
                else//Otherwise, delete the key value pair
                {
                    string[] keyNames = key.GetValueNames();
                    foreach (string keyName in keyNames)
                    {
                        if (keyName.ToUpper() == exeName.ToUpper())
                        {
                            key.DeleteValue(exeName);
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string ss = ex.Message;
                return false;
                //throw;
            }
 
            return true;
        }

3. How to obtain administrator rights please refer to

How to run the program as an administrator - cool kids - blog Park https://www.cnblogs.com/babycool/p/3569183.html

C ා program runs with administrator's permission - Cosmo ා spy - blog Park https://www.cnblogs.com/Interkey/p/RunAsAdmin.html

4. The actual measurement is stable and available. I hope it can help you. Thank you for your support.

Reprint: https://blog.csdn.net/liyu3519/article/details/81257839

Keywords: C# Windows shell

Added by Irresistable on Thu, 02 Jan 2020 01:48:05 +0200