C# 推荐一种开机自启动的方式
-
概述
网上多数搜索结果以注册表设置为优先,这个方法需要管理员权限,实际工作中可能并不适用。这个方法是直接写到用户开机自启动目录里,系统开机会带着一起启动。转载请注明出处,谢谢。
-
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /// <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 ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)