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;
    }
}
相关推荐
"菠萝"17 分钟前
C#知识学习-017(修饰符_6)
学习·c#
VB.Net44 分钟前
C#循序渐进
开发语言·c#
feifeigo1232 小时前
C# WinForms实现模拟叫号系统
c#
helloworddm3 小时前
Orleans 流系统握手机制时序图
后端·c#
William_cl3 小时前
【C# OOP 入门到精通】从基础概念到 MVC 实战(含 SOLID 原则与完整代码)
开发语言·c#·mvc
YuanlongWang8 小时前
c# 泛型的详细介绍
c#
嵌入式学习和实践10 小时前
C# WinForms 多窗口交互通信的示例-主窗口子窗口交互通信
c#·交互·主窗口-子窗口通信
专注VB编程开发20年10 小时前
C#,VB.NET数组去重复,提取键名和重复键和非重复键
c#·.net·linq·取唯一键·去重复·重复数量
YuanlongWang11 小时前
Entity Framework Core和SqlSugar的区别,详细介绍
c#
unicrom_深圳市由你创科技14 小时前
工业上位机,用Python+Qt还是C#+WPF?
python·qt·c#