C#實現軟體開機自啟動(不需要管理員許可權)

来源:https://www.cnblogs.com/timefiles/archive/2023/07/01/17519239.html
-Advertisement-
Play Games

[TOC] # 原理簡介 本文參考[C#/WPF/WinForm/程式實現軟體開機自動啟動的兩種常用方法](https://blog.csdn.net/weixin_42288432/article/details/120059296),將裡面中的第一種方法做了封裝成**AutoStart**類,使 ...


目錄

原理簡介

本文參考C#/WPF/WinForm/程式實現軟體開機自動啟動的兩種常用方法,將裡面中的第一種方法做了封裝成AutoStart類,使用時直接兩三行代碼就可以搞定。

自啟動的原理是將軟體的快捷方式創建到電腦的自動啟動目錄下(不需要管理員許可權),這種方法更加通用、限制更少。

使用方法

使用方法如下:

//快捷方式的描述、名稱的預設值是當前的進程名,自啟動預設為正常視窗,一般情況下不需要手動設置
//設置快捷方式的描述,
AutoStart.Instance.QuickDescribe = "軟體描述";
//設置快捷方式的名稱
AutoStart.Instance.QuickName = "軟體名稱";
//設置自啟動的視窗類型,後臺服務類的軟體可以設置為最小視窗
AutoStart.Instance.WindowStyle = WshWindowStyle.WshMinimizedFocus;

//快捷方式設置true時,有就忽略、沒有就創建,自啟動快捷方式只能存在一個
//設置開機自啟動,true 自啟動,false 不自啟動
AutoStart.Instance.SetAutoStart(SysParam.Instance.OnOff);
//設置桌面快捷方式,true 創建桌面快捷方式(有就跳過,沒有就創建),false 刪除桌面快捷方式
AutoStart.Instance.SetDesktopQuick(true);

完整代碼

引用以下命名空間:

//添加引用,在 Com 中搜索 Windows Script Host Object Model
using IWshRuntimeLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

AutoStart類代碼:

public class AutoStart
{
    #region 公開

    /// <summary>
    /// 唯一實例,也可以自定義實例
    /// </summary>
    public static AutoStart Instance { get; private set; } = new AutoStart();

    /// <summary>
    /// 快捷方式描述,預設值是當前的進程名
    /// </summary>
    public string QuickDescribe { get; set; } = Process.GetCurrentProcess().ProcessName;

    /// <summary>
    /// 快捷方式名稱,預設值是當前的進程名
    /// </summary>
    public string QuickName { get; set; } = Process.GetCurrentProcess().ProcessName;

    /// <summary>
    /// 自啟動視窗類型,預設值是正常視窗
    /// </summary>
    public WshWindowStyle WindowStyle { get; set; } = WshWindowStyle.WshNormalFocus;

    /// <summary>
    /// 設置開機自動啟動-只需要調用改方法就可以了參數裡面的bool變數是控制開機啟動的開關的,預設為開啟自啟啟動
    /// </summary>
    /// <param name="onOff">自啟開關</param>
    public void SetAutoStart(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, QuickDescribe,WindowStyle);
            }
        }
        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>
    public void SetDesktopQuick(bool isCreate)
    {
        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appAllPath);
        if (isCreate)
        {
            //沒有就創建
            if (shortcutPaths.Count < 1)
            {
                CreateShortcut(desktopPath, QuickName, appAllPath, QuickDescribe, WshWindowStyle.WshNormalFocus);
            }
        }
        else
        {
            //有就刪除
            for (int i = 0; i < shortcutPaths.Count; i++)
            {
                DeleteFile(shortcutPaths[i]);
            }
        }
    }

    #endregion 公開

    #region 私有

    /// <summary>
    /// 自動獲取系統自動啟動目錄
    /// </summary>
    private string systemStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

    /// <summary>
    /// 自動獲取程式完整路徑
    /// </summary>
    private string appAllPath = Process.GetCurrentProcess().MainModule.FileName;

    /// <summary>
    /// 自動獲取桌面目錄
    /// </summary>
    private string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    /// <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, WshWindowStyle windowStyle, string iconLocation = null)
    {
        try
        {
            //目錄不存在則創建
            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
            //合成路徑
            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            //存在則不創建
            if (System.IO.File.Exists(shortcutPath)) return true;
            //添加引用 Com 中搜索 Windows Script Host Object Model
            WshShell shell = new IWshRuntimeLibrary.WshShell();
            //創建快捷方式對象
            IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);
            //指定目標路徑
            shortcut.TargetPath = targetPath;
            //設置起始位置
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);
            //設置運行方式,預設為常規視窗
            shortcut.WindowStyle = (int)windowStyle;
            //設置備註
            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);
        }
    }

    #endregion 私有
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 不知不覺,《C++面試八股文》已經更新30篇了,這是我第一次寫技術博客,由於個人能力有限,出現了不少紕漏,在此向各位讀者小伙伴們致歉。 為了不誤導更多的小伙伴,以後會不定期的出勘誤文章,請各位小伙伴留意。 在《[C++面試八股文:C++中,設計一個類要註意哪些東西?](https://zhuanla ...
  • 前言 在併發編程中,我們經常會遇到多個goroutine同時操作一個map的情況。如果在這種情況下直接使用普通的map,那麼就可能會引發競態條件,造成數據不一致或者更嚴重的問題。 sync.Map是Go語言中內置的一種併發安全的map,但是他的實現和用法與普通的map完全不同,這篇文章將詳細介紹這些 ...
  • ## Thinkphp6 連接達夢資料庫 這裡使用 IDEA phpEnv PHP7.3 Thinkphp6 桌面操作系統:Windows11 虛擬機:VMware 伺服器操作系統:銀河麒麟 在虛擬機操作與windows無異 [參考資料](https://blog.csdn.net/chenxuan ...
  • ## ThinkPHP6.0 鏈式SQL語句 #### 查詢單個數據 ```php $user = Db::query('select * from `user`'); $user=Db::table('user')->where('UserID',1001)->find();//查詢結果為空 返回 ...
  • 1. sort函數 sort函數為python內置的列表排序高階函數,所謂高階函數,也就是參數為函數或返回值為函數。 先看個簡單的例子: # 數字列表的排序示例nums = [5, 2, 9, 1, 7] nums.sort()print(nums) # 輸出:[1, 2, 5, 7, 9] 可以發 ...
  • 我們開源了組件的源代碼,希望更多人能更便捷的使用開源組件,最好的辦法當然是把組件的JAR包上傳到Maven中央倉庫,這樣可直接通過Maven/Gradle等方式快速引用和使用。但是要把JAR包上傳到Maven中央倉庫的門檻比較高,本文介紹一種非常簡單的使用GitHub/Gitee作為Maven倉庫的... ...
  • # 1. JVM快速入門 從面試開始: 1. 請談談你對JVM 的理解?java8 的虛擬機有什麼更新? 2. 什麼是OOM ?什麼是StackOverflowError?有哪些方法分析? 3. JVM 的常用參數調優你知道哪些? 4. 記憶體快照抓取和MAT分析DUMP文件知道嗎? 5. 談談JVM ...
  • 繼上篇:Taurus .Net Core 微服務開源框架:Admin 插件【4-2】 - 配置管理-Mvc【含請求日誌列印】,本篇繼續介紹下一個內容:系統配置節點:Mvc - Plugin - MicroService 配置界面:註冊中心 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...