将程序加到启动组

有时需要将程序设置成随系统启动,最简单的一种就是放在  程序-->启动组里面。

其实就是创建一个快捷方式而已, 呵呵

我们需要一个 com 组件,  名叫 "Window Script Host Object Model ", 将它加入引用中

代码就很简单了, 为了方便调用, 将它写成一个函数
/// <summary>
        
/// 将程序的快捷方式添加到启动组
        
/// </summary>
        
/// <param name="fullPath">程序全路径</param>

        private void AddShortCutToStartup(string fullPath)
        
{
            
if (string.IsNullOrEmpty(fullPath))
                
return;
            IWshRuntimeLibrary.WshShell shell 
= new IWshRuntimeLibrary.WshShell();
            
try
            
{
                
//取得快捷方式的路径
                
//快捷方式其实是一个后缀为 lnk 的文件
                string link = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup)
            , Path.GetFileNameWithoutExtension(fullPath) 
+ ".lnk");
                
if (!File.Exists(link))
                
{
                    IWshRuntimeLibrary.IWshShortcut shortCut 
= (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(link);
                    
//设置目标路径
                    
//shortCut 还有很多方法,比如 HotKey, IconLocation 等等,不再赘述
                    shortCut.TargetPath = fullPath;
                    shortCut.WindowStyle 
= 1;
                    shortCut.Save();
                }

            }

            
catch (Exception ex)
            
{
                log.Error(
"AddShortCutToStartup Error: " + ex.Message);
            }

        }

如果要将本程序做成自启动, 只需要在 Form_Load 中加一行代码就行了

AddShortCutToStartup(Application.ExecutablePath);

原文地址:https://www.cnblogs.com/michaelhuwei/p/1185598.html