C#实现软件开机自启动(不需要管理员权限)

这篇具有很好参考价值的文章主要介绍了C#实现软件开机自启动(不需要管理员权限)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录
  • 原理简介
  • 使用方法
  • 完整代码

原理简介

本文参考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类代码:文章来源地址https://www.toymoban.com/news/detail-513385.html

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 私有
}

到了这里,关于C#实现软件开机自启动(不需要管理员权限)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ubuntu开机出现《系统出错且无法恢复,请联系系统管理员。》错误解决办法!

    背景: ubuntu22.04.2命令行,执行自动安装系统推荐显卡驱动命令,字体变大,重启后出现如下图错误,无法进入系统,无法通过CTRL+ALT+F1-F3进入TTY模式。 解决办法: 1.首先要想办法进入系统,能输入命令检查。 方法一:按CTRL+ALT+F1-3进入TTY模式,输入命令。(行不通) 方法二

    2024年04月23日
    浏览(39)
  • Windows开发:服务程序启动有管理员权限的界面程序

    本章介绍Windows桌面开发中,服务程序如何启动有管理员权限的界面进程。 在这种情况下,以下几点需要弄清楚: Windows的服务是什么 Microsoft Windows 服务(过去称为 NT 服务)允许用户创建可在其自身的 Windows 会话中长时间运行的可执行应用程序。 这些服务可在计算机启动时自

    2024年02月11日
    浏览(51)
  • linux环境minio安装启动,管理员登录,nginx代理

    一.下载minio 官网下载:  MinIO | Code and downloads to create high performance object storage  直接点击下载或者用wget https://dl.min.io/server/minio/release/linux-amd64/minio 最后都是得到一个文件minio(大概100M) 二.启动minio 1.创建文件夹,比如 2.将第一步得到的minio放到上面目录下 3.给该文件夹赋权限  

    2023年04月24日
    浏览(59)
  • Win10 安装软件报错:管理员已阻止你运行此应用

    win10 下安装软件出现以下报错:                 管理员已阻止你运行此应用。有关详细信息,请与管理员联系。  解决方法:  直接在cmd 控制台下输入命令进行安装(即直接输入安装文件的路径地址) 这样就是用管理员权限进行安装应用 但是我这里通过cmd 进行安装

    2024年02月11日
    浏览(61)
  • 银河麒麟高级服务器操作系统V10-系统管理员手册:04 安装和管理软件

    目录 第四章 安装和管理软件 4.1. 检查和升级软件包 4.1.1. 软件包升级检查 4.1.2. 升级软件包 4.1.3. 利用系统光盘与 dnf 离线升级系统 4.2. 管理软件包 4.2.1. 检索软件包 4.2.2. 安装包列表 4.2.3. 显示软件包信息 4.2.4. 安装软件包 4.2.5. 下载软件包 4.2.6. 删除软件包 4.3. 管理软件包组

    2024年02月03日
    浏览(51)
  • Win10和Win11上设置VS(Visual Studio)默认以管理员权限权限启动设置方法

    如果只需要当前启动为管理员权限,方法如下: 1、使用“开始”菜单 2、根据所使用的 Windows操作系统 版本,执行以下步骤之一: 在 Windows 10 中,打开“开始”菜单,然后滚动到 Visual Studio。 在“Windows 11”中,选择“开始”按钮,然后在“搜索”框中键入“Visual Studio”。

    2024年02月11日
    浏览(66)
  • 安装mysql服务出现Install/Remove of the Service Denied!问题,即使管理员启动cmd也无效

    在Windows系统下,如果你是以管理员身份运行cmd,但是仍然无法安装MySQL服务,可能是因为系统的用户账户控制(UAC)设置的问题。你可以尝试以管理员权限运行命令提示符(cmd),然后使用以下命令禁用UAC: reg add HKLMSOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem /v EnableLUA /t REG_DWO

    2024年02月15日
    浏览(38)
  • Arcgis10.2.2安装过程中ArcGIS license Server Administrator(许可服务器管理员)无法启动解决办法

    在安装Arcgis10.2.2时,按照此方法: ArcGIS Desktop10.2的安装与基本使用 进行安装,在重新启动ArcGIS license Server Administrator(许可服务器管理员)导入许可时无法启动,点击启动没有反应。 搜索了一些解决办法,但都没有效果,最后查看破解文件中的 service.txt 文件发现,文件第三行

    2024年03月27日
    浏览(48)
  • MySQL启动服务时发生系统错误 5,拒绝访问且管理员权限无效、net start mysql 服务名无效解决方法

    在重启MySQL服务后,报错 启动服务时发生系统错误 5,拒绝访问 网上查询解决办法都是使用管理员权限开启CMD运行 net start mysql 会报错 服务名无效 ,解决办法为修改为 net start mysqlXX ,XX为版本号,如我的8.0就是 net start mysql80 运行后仍然会报错 启动服务时发生系统错误 5,拒

    2024年02月01日
    浏览(38)
  • 模拟Linux文件管理员系统-shell实现

    目录 模拟Linux文件管理员系统-shell实现 1 系统要求 2 脚本执行效果 2.1 管理员登录效果 2.2 普通用户登录效果 2.3 密码文件格式 3 实现脚本 4 密码文件 5 说明 注:此脚本仅供学习使用,具体需要根据实际情况进行测试调整。 用空格隔开,从左往右依次为: 用户名 密码 是否为

    2024年02月12日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包