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;
    }
}
相关推荐
Ljugg12 分钟前
把doi直接插入word中,然后直接生成参考文献
开发语言·c#·word
厦门德仔1 小时前
【C#】C#字符串拼接的6种方式及其性能分析对比
服务器·windows·c#
画个逗号给明天"2 小时前
C#从入门到精通(5)
开发语言·笔记·c#
鲤籽鲲6 小时前
C# System.Net.IPEndPoint 使用详解
网络·microsoft·c#·.net
快乐点吧6 小时前
【Word】批注一键导出:VBA 宏
开发语言·c#·word
Dm_dotnet6 小时前
为Avalonia应用添加图标
c#
Rabbb7 小时前
C# 切割数组的Linq扩展方法 Period,PeriodBy
后端·c#
阿ฅ( ̳• ε • ̳)ฅ8 小时前
C#窗体应用程序连接数据库
开发语言·数据库·c#
勘察加熊人12 小时前
wpf+c#路径迷宫鼠标绘制
开发语言·c#·wpf
小黄人软件13 小时前
C# ini文件全自动界面配置:打开界面时读ini配置到界面各控件,界面上的控件根据ini文件内容自动生成,点保存时把界面各控件的值写到ini里。
开发语言·c#