C# 推荐一种开机自启动的方式

概述(Overview)

网上多数搜索结果以注册表设置为优先,这个方法需要管理员权限,实际工作中可能并不适用。这个方法是直接写到用户开机自启动目录里,系统开机会带着一起启动。(Most search results on the web are based on registry preferences, which requires administrator privileges and may not be applicable in practice. This method is written directly to the user's boot directory, and the system boot will be started with it.)

代码(Code):

复制代码
/// <summary>
/// 设置程序自动运行
/// </summary>
/// <param name="IsAppAutoStart">是否开机自启动</param>
public static bool SetAppAutoRun(bool IsAppAutoStart=true)
{
        string sourseEXE = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestApp.exe");
        string startup_ShortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\TestApp.lnk";
        if (IsAppAutoStart)//需要创建开机自启动
        {
            if (File.Exists(startup_ShortcutPath))
            {
                File.Delete(startup_ShortcutPath);
            }
            CreateShortcut(sourseEXE, startup_ShortcutPath);
        }
        else
        {
            if (File.Exists(startup_ShortcutPath))
            {
                File.Delete(startup_ShortcutPath);
            }
        }
}

/// <summary>
/// 创建一个快捷方式(用户级别)
/// </summary>
/// <param name="targetPath">目标程序路径.exe</param>
/// <param name="shortcutPath">快捷方式放置路径.lnk</param>
private static bool CreateShortcut(string targetPath, string shortcutPath)
{
    try
    {
     //反射
        var shellType = Type.GetTypeFromProgID("WScript.Shell");//这是windows自带的快捷方式生成程序,可以直接借用
        dynamic shell = Activator.CreateInstance(shellType);
        var shortcut = shell.CreateShortcut(shortcutPath);
        shortcut.TargetPath = targetPath;
        //shortcut.Arguments = "在路径后面追加的参数 空格分隔";
        //shortcut.Description = "备注信息";
        //shortcut.WindowStyle = FormWindowState.Normal;
        //shortcut.IconLocation = "图标路径";

        shortcut.Save();

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}
相关推荐
且听风吟ayan1 小时前
leetcode day20 滑动窗口209+904
算法·leetcode·c#
GISer_Qing4 小时前
ASP.NET Core 8.0学习笔记(二十七)——数据迁移:Migrations深入与其他迁移命令
数据库·c#·.netcore·entityframework
追烽少年x5 小时前
C# WinForm 中的事件驱动模型
c#
CE贝多芬6 小时前
WPF的页面设计和实用功能实现
c#·wpf
code_shenbing7 小时前
WPF 实现虚拟键盘
c#·wpf
软件黑马王子13 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
水煮庄周鱼鱼18 小时前
C# 入门简介
开发语言·c#
软件黑马王子19 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter19 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu2021 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq