经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C# 推荐一种开机自启动的方式
来源:cnblogs  作者:tpen  时间:2024/7/29 9:21:43  对本文有异议
  • 概述(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):

  1. /// <summary>
  2. /// 设置程序自动运行
  3. /// </summary>
  4. /// <param name="IsAppAutoStart">是否开机自启动</param>
  5. public static bool SetAppAutoRun(bool IsAppAutoStart=true)
  6. {
  7. string sourseEXE = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestApp.exe");
  8. string startup_ShortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\TestApp.lnk";
  9. if (IsAppAutoStart)//需要创建开机自启动
  10. {
  11. if (File.Exists(startup_ShortcutPath))
  12. {
  13. File.Delete(startup_ShortcutPath);
  14. }
  15. CreateShortcut(sourseEXE, startup_ShortcutPath);
  16. }
  17. else
  18. {
  19. if (File.Exists(startup_ShortcutPath))
  20. {
  21. File.Delete(startup_ShortcutPath);
  22. }
  23. }
  24. }
  25.  
  26. /// <summary>
  27. /// 创建一个快捷方式(用户级别)
  28. /// </summary>
  29. /// <param name="targetPath">目标程序路径.exe</param>
  30. /// <param name="shortcutPath">快捷方式放置路径.lnk</param>
  31. private static bool CreateShortcut(string targetPath, string shortcutPath)
  32. {
  33. try
  34. {
         //反射
  35. var shellType = Type.GetTypeFromProgID("WScript.Shell");//这是windows自带的快捷方式生成程序,可以直接借用
  36. dynamic shell = Activator.CreateInstance(shellType);
  37. var shortcut = shell.CreateShortcut(shortcutPath);
  38. shortcut.TargetPath = targetPath;
  39. //shortcut.Arguments = "在路径后面追加的参数 空格分隔";
  40. //shortcut.Description = "备注信息";
  41. //shortcut.WindowStyle = FormWindowState.Normal;
  42. //shortcut.IconLocation = "图标路径";
  43.  
  44. shortcut.Save();
  45.  
  46. return true;
  47. }
  48. catch (Exception ex)
  49. {
  50. return false;
  51. }
  52. }

原文链接:https://www.cnblogs.com/tpen/p/18329327

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号