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;
    }
}
相关推荐
夏霞8 小时前
IIS 应用程序池 3 种标识:ApplicationPoolIdentity / LocalSystem / LocalService 权限区别(超清晰)
c#·.net
SteveDraw8 小时前
常见的设计模式及工业场景下应用(更新中)
设计模式·c#·编码规范·gof23
weixin_5206498717 小时前
WinForm数据展示组件ListView
c#
程序设计实验室1 天前
Spark.NET:一个试图把 Django / Rails 式开发体验带回 .NET 世界的全栈 Web 框架。
c#
byoass1 天前
智巢AI知识库深度解析:企业文档管理从大海捞针到精准狙击的进化之路
开发语言·网络·人工智能·安全·c#·云计算
njsgcs1 天前
solidworks自动标注折弯4 无向图 c#
开发语言·c#·solidworks
我是唐青枫1 天前
C#.NET ThreadLocal 深入解析:线程独享数据、性能收益与实战边界
c#·.net
JQLvopkk1 天前
C# 工业级上位机:交互实战
开发语言·c#·交互
kingwebo'sZone1 天前
PdfiumViewer使用权限控制期操作按钮(PdfViewer其实也可以完整兼容)
c#
张小俊_1 天前
WPF 跨线程 UI 更新与硬编码赋值引发的 Bug 排查
c#·bug·wpf