C#程式實現軟體開機自動啟動的兩種常用方法

38度6發表於2018-08-22

C#/WPF/WinForm/.NET程式程式碼實現軟體程式開機自動啟動的兩種常用方法函式的示例與例項帶詳細註釋

方法一:將軟體的快捷方式建立到計算機的自動啟動目錄下(不需要管理員許可權)

1.必要引用

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

2.程式碼實現-只需要呼叫SetMeAutoStart(bool onOff)方法就可以了,引數onOff表示自啟開關

        /// <summary>
        /// 快捷方式名稱-任意自定義
        /// </summary>
        private const string QuickName = "TCNVMClient";
 
        /// <summary>
        /// 自動獲取系統自動啟動目錄
        /// </summary>
        private string systemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }
 
        /// <summary>
        /// 自動獲取程式完整路徑
        /// </summary>
        private string appAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }
 
        /// <summary>
        /// 自動獲取桌面目錄
        /// </summary>
        private string desktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }
 
        /// <summary>
        /// 設定開機自動啟動-只需要呼叫改方法就可以了引數裡面的bool變數是控制開機啟動的開關的,預設為開啟自啟啟動
        /// </summary>
        /// <param name="onOff">自啟開關</param>
        public void SetMeAutoStart(bool onOff = true)
        {
            if (onOff)//開機啟動
            {
                //獲取啟動路徑應用程式快捷方式的路徑集合
                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //存在2個以快捷方式則保留一個快捷方式-避免重複多於
                if (shortcutPaths.Count >= 2)
                {
                    for (int i = 1; i < shortcutPaths.Count; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
                else if (shortcutPaths.Count < 1)//不存在則建立快捷方式
                {
                    CreateShortcut(systemStartPath, QuickName, appAllPath, "中吉售貨機");
                }
            }
            else//開機不啟動
            {
                //獲取啟動路徑應用程式快捷方式的路徑集合
                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
                //存在快捷方式則遍歷全部刪除
                if (shortcutPaths.Count > 0)
                {
                    for (int i = 0; i < shortcutPaths.Count; i++)
                    {
                        DeleteFile(shortcutPaths[i]);
                    }
                }
            }
            //建立桌面快捷方式-如果需要可以取消註釋
            //CreateDesktopQuick(desktopPath, QuickName, appAllPath);
        }
 
        /// <summary>
        ///  向目標路徑建立指定檔案的快捷方式
        /// </summary>
        /// <param name="directory">目標目錄</param>
        /// <param name="shortcutName">快捷方式名字</param>
        /// <param name="targetPath">檔案完全路徑</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">圖示地址</param>
        /// <returns>成功或失敗</returns>
        private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
        {
            try
            {
                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);                         //目錄不存在則建立
                //新增引用 Com 中搜尋 Windows Script Host Object Model
                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));          //合成路徑
                WshShell shell = new IWshRuntimeLibrary.WshShell();
                IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);    //建立快捷方式物件
                shortcut.TargetPath = targetPath;                                                               //指定目標路徑
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);                                  //設定起始位置
                shortcut.WindowStyle = 1;                                                                       //設定執行方式,預設為常規視窗
                shortcut.Description = description;                                                             //設定備註
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;    //設定圖示路徑
                shortcut.Save();                                                                                //儲存快捷方式
                return true;
            }
            catch(Exception ex)
            {
                string temp = ex.Message;
                temp = "";
            }
            return false;
        }
 
        /// <summary>
        /// 獲取指定資料夾下指定應用程式的快捷方式路徑集合
        /// </summary>
        /// <param name="directory">資料夾</param>
        /// <param name="targetPath">目標應用程式路徑</param>
        /// <returns>目標應用程式的快捷方式</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>
        /// 獲取快捷方式的目標檔案路徑-用於判斷是否已經開啟了自動啟動
        /// </summary>
        /// <param name="shortcutPath"></param>
        /// <returns></returns>
        private string GetAppPathFromQuick(string shortcutPath)
        {
            //快捷方式檔案的路徑 = @"d:Test.lnk";
            if (System.IO.File.Exists(shortcutPath))
            {
                WshShell shell = new WshShell();
                IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
                //快捷方式檔案指向的路徑.Text = 當前快捷方式檔案IWshShortcut類.TargetPath;
                //快捷方式檔案指向的目標目錄.Text = 當前快捷方式檔案IWshShortcut類.WorkingDirectory;
                return shortct.TargetPath;
            }
            else
            {
                return "";
            }
        }
 
        /// <summary>
        /// 根據路徑刪除檔案-用於取消自啟時從計算機自啟目錄刪除程式的快捷方式
        /// </summary>
        /// <param name="path">路徑</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>
        /// 在桌面上建立快捷方式-如果需要可以呼叫
        /// </summary>
        /// <param name="desktopPath">桌面地址</param>
        /// <param name="appPath">應用路徑</param>
        public void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")
        {
            List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);
            //如果沒有則建立
            if (shortcutPaths.Count < 1)
            {
                CreateShortcut(desktopPath, quickName, appPath, "軟體描述");
            }
        }

方法二:修改計算機登錄檔的方式(需要管理員許可權)

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

2.程式碼實現-只需要呼叫SetMeStart(bool onOff)方法就可以了,引數onOff表示自啟開關

/// <summary>
        /// 將本程式設為開啟自啟
        /// </summary>
        /// <param name="onOff">自啟開關</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>
        /// 將應用程式設為或不設為開機啟動
        /// </summary>
        /// <param name="onOff">自啟開關</param>
        /// <param name="appName">應用程式名</param>
        /// <param name="appPath">應用程式完全路徑</param>
        public static bool SetAutoStart(bool onOff, string appName, string appPath)
        {
            bool isOk = true;
            //如果從沒有設為開機啟動設定到要設為開機啟動
            if (!IsExistKey(appName) && onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            //如果從設為開機啟動設定到不要設為開機啟動
            else if (IsExistKey(appName) && !onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            return isOk;
        }
 
        /// <summary>
        /// 判斷註冊鍵值對是否存在,即是否處於開機啟動狀態
        /// </summary>
        /// <param name="keyName">鍵值名</param>
        /// <returns></returns>
        private static bool IsExistKey(string keyName)
        {
            try
            {
                bool _exist = false;
                RegistryKey local = Registry.LocalMachine;
                RegistryKey runs = local.OpenSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun", 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>
        /// 寫入或刪除登錄檔鍵值對,即設為開機啟動或開機不啟動
        /// </summary>
        /// <param name="isStart">是否開機啟動</param>
        /// <param name="exeName">應用程式名</param>
        /// <param name="path">應用程式路徑帶程式名</param>
        /// <returns></returns>
        private static bool SelfRunning(bool isStart, string exeName, string path)
        {
            try
            {
                RegistryKey local = Registry.LocalMachine;
                RegistryKey key = local.OpenSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun", true);
                if (key == null)
                {
                    local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");
                }
                //若開機自啟動則新增鍵值對
                if (isStart)
                {
                    key.SetValue(exeName, path);
                    key.Close();
                }
                else//否則刪除鍵值對
                {
                    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.如何獲取管理員許可權請參考

C#如何以管理員身份執行程式 – 酷小孩 – 部落格園  https://www.cnblogs.com/babycool/p/3569183.html

C#程式以管理員許可權執行 – Cosmic_Spy – 部落格園  https://www.cnblogs.com/Interkey/p/RunAsAdmin.html

4.實測穩定可用,希望對你有幫助,謝謝支援。

轉載:https://blog.csdn.net/liyu3519/article/details/81257839

相關文章