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;
    }
}
相关推荐
黑夜中的潜行者2 小时前
构建高性能 WPF 大图浏览器:TiledViewer 技术解密
性能优化·c#·.net·wpf·图形渲染
LongtengGensSupreme3 小时前
C# 中监听 IPv6 回环地址(Loopback Address)----socket和tcp
c#·ipv6 回环地址
就是有点傻3 小时前
C#中如何和西门子通信
开发语言·c#
海底星光3 小时前
c#进阶疗法 -jwt+授权
c#
液态不合群3 小时前
如何提升 C# 应用中的性能
开发语言·算法·c#
多多*4 小时前
计算机网络相关 讲一下rpc与传统http的区别
java·开发语言·网络·jvm·c#
阿蒙Amon4 小时前
C#每日面试题-简述反射
开发语言·面试·c#
缺点内向4 小时前
告别“复制粘贴”:用C#和模板高效生成Word文档
开发语言·c#·word
海底星光5 小时前
c#进阶疗法 -自定义鉴权
c#
FuckPatience5 小时前
C# .csproj Baseoutputpath/Outputpath、AppendTargetFrameworkToOutputPath
c#