欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#程序实现软件开机自动启动的两种常用方法

程序员文章站 2022-03-17 09:28:31
C#/WPF/WinForm/.NET程序代码实现软件程序开机自动启动的两种常用方法函数的示例与实例带详细注释 方法一:将软件的快捷方式创建到计算机的自动启动目录下(不需要管理员权限) 1.必要引用 2.代码实现-只需要调用SetMeAutoStart(bool onOff)方法就可以了,参数onO ......

c#/wpf/winform/.net程序代码实现软件程序开机自动启动的两种常用方法函数的示例与实例带详细注释

方法一:将软件的快捷方式创建到计算机的自动启动目录下(不需要管理员权限)

1.必要引用

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.io;
using iwshruntimelibrary;
using system.diagnostics;

2.代码实现-只需要调用setmeautostart(bool onoff)方法就可以了,参数onoff表示自启开关

        /// <summary>
        /// 快捷方式名称-任意自定义
        /// </summary>
        private const string quickname = "tcnvmclient";
 
        /// <summary>
        /// 自动获取系统自动启动目录
        /// </summary>
        private string systemstartpath { get { return environment.getfolderpath(environment.specialfolder.startup); } }
 
        /// <summary>
        /// 自动获取程序完整路径
        /// </summary>
        private string appallpath { get { return process.getcurrentprocess().mainmodule.filename; } }
 
        /// <summary>
        /// 自动获取桌面目录
        /// </summary>
        private string desktoppath { get { return environment.getfolderpath(environment.specialfolder.desktopdirectory); } }
 
        /// <summary>
        /// 设置开机自动启动-只需要调用改方法就可以了参数里面的bool变量是控制开机启动的开关的,默认为开启自启启动
        /// </summary>
        /// <param name="onoff">自启开关</param>
        public void setmeautostart(bool onoff = true)
        {
            if (onoff)//开机启动
            {
                //获取启动路径应用程序快捷方式的路径集合
                list<string> shortcutpaths = getquickfromfolder(systemstartpath, appallpath);
                //存在2个以快捷方式则保留一个快捷方式-避免重复多于
                if (shortcutpaths.count >= 2)
                {
                    for (int i = 1; i < shortcutpaths.count; i++)
                    {
                        deletefile(shortcutpaths[i]);
                    }
                }
                else if (shortcutpaths.count < 1)//不存在则创建快捷方式
                {
                    createshortcut(systemstartpath, quickname, appallpath, "中吉售货机");
                }
            }
            else//开机不启动
            {
                //获取启动路径应用程序快捷方式的路径集合
                list<string> shortcutpaths = getquickfromfolder(systemstartpath, appallpath);
                //存在快捷方式则遍历全部删除
                if (shortcutpaths.count > 0)
                {
                    for (int i = 0; i < shortcutpaths.count; i++)
                    {
                        deletefile(shortcutpaths[i]);
                    }
                }
            }
            //创建桌面快捷方式-如果需要可以取消注释
            //createdesktopquick(desktoppath, quickname, appallpath);
        }
 
        /// <summary>
        ///  向目标路径创建指定文件的快捷方式
        /// </summary>
        /// <param name="directory">目标目录</param>
        /// <param name="shortcutname">快捷方式名字</param>
        /// <param name="targetpath">文件完全路径</param>
        /// <param name="description">描述</param>
        /// <param name="iconlocation">图标地址</param>
        /// <returns>成功或失败</returns>
        private bool createshortcut(string directory, string shortcutname, string targetpath, string description = null, string iconlocation = null)
        {
            try
            {
                if (!directory.exists(directory)) directory.createdirectory(directory);                         //目录不存在则创建
                //添加引用 com 中搜索 windows script host object model
                string shortcutpath = path.combine(directory, string.format("{0}.lnk", shortcutname));          //合成路径
                wshshell shell = new iwshruntimelibrary.wshshell();
                iwshshortcut shortcut = (iwshruntimelibrary.iwshshortcut)shell.createshortcut(shortcutpath);    //创建快捷方式对象
                shortcut.targetpath = targetpath;                                                               //指定目标路径
                shortcut.workingdirectory = path.getdirectoryname(targetpath);                                  //设置起始位置
                shortcut.windowstyle = 1;                                                                       //设置运行方式,默认为常规窗口
                shortcut.description = description;                                                             //设置备注
                shortcut.iconlocation = string.isnullorwhitespace(iconlocation) ? targetpath : iconlocation;    //设置图标路径
                shortcut.save();                                                                                //保存快捷方式
                return true;
            }
            catch(exception ex)
            {
                string temp = ex.message;
                temp = "";
            }
            return false;
        }
 
        /// <summary>
        /// 获取指定文件夹下指定应用程序的快捷方式路径集合
        /// </summary>
        /// <param name="directory">文件夹</param>
        /// <param name="targetpath">目标应用程序路径</param>
        /// <returns>目标应用程序的快捷方式</returns>
        private list<string> getquickfromfolder(string directory, string targetpath)
        {
            list<string> tempstrs = new list<string>();
            tempstrs.clear();
            string tempstr = null;
            string[] files = directory.getfiles(directory, "*.lnk");
            if (files == null || files.length < 1)
            {
                return tempstrs;
            }
            for (int i = 0; i < files.length; i++)
            {
                //files[i] = string.format("{0}\\{1}", directory, files[i]);
                tempstr = getapppathfromquick(files[i]);
                if (tempstr == targetpath)
                {
                    tempstrs.add(files[i]);
                }
            }
            return tempstrs;
        }
 
        /// <summary>
        /// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动
        /// </summary>
        /// <param name="shortcutpath"></param>
        /// <returns></returns>
        private string getapppathfromquick(string shortcutpath)
        {
            //快捷方式文件的路径 = @"d:\test.lnk";
            if (system.io.file.exists(shortcutpath))
            {
                wshshell shell = new wshshell();
                iwshshortcut shortct = (iwshshortcut)shell.createshortcut(shortcutpath);
                //快捷方式文件指向的路径.text = 当前快捷方式文件iwshshortcut类.targetpath;
                //快捷方式文件指向的目标目录.text = 当前快捷方式文件iwshshortcut类.workingdirectory;
                return shortct.targetpath;
            }
            else
            {
                return "";
            }
        }
 
        /// <summary>
        /// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式
        /// </summary>
        /// <param name="path">路径</param>
        private void deletefile(string path)
        {
            fileattributes attr = system.io. file.getattributes(path);
            if (attr == fileattributes.directory)
            {
                directory.delete(path, true);
            }
            else
            {
                system.io.file.delete(path);
            }
        }
 
        /// <summary>
        /// 在桌面上创建快捷方式-如果需要可以调用
        /// </summary>
        /// <param name="desktoppath">桌面地址</param>
        /// <param name="apppath">应用路径</param>
        public void createdesktopquick(string desktoppath = "", string quickname = "", string apppath = "")
        {
            list<string> shortcutpaths = getquickfromfolder(desktoppath, apppath);
            //如果没有则创建
            if (shortcutpaths.count < 1)
            {
                createshortcut(desktoppath, quickname, apppath, "软件描述");
            }
        }

方法二:修改计算机注册表的方式(需要管理员权限)

using microsoft.win32;
using system;
using system.windows.forms;
using system.diagnostics;

2.代码实现-只需要调用setmestart(bool onoff)方法就可以了,参数onoff表示自启开关

/// <summary>
        /// 将本程序设为开启自启
        /// </summary>
        /// <param name="onoff">自启开关</param>
        /// <returns></returns>
        public static bool setmestart(bool onoff)
        {
            bool isok = false;
            string appname = process.getcurrentprocess().mainmodule.modulename;
            string apppath = process.getcurrentprocess().mainmodule.filename;
            isok = setautostart(onoff, appname, apppath);
            return isok;
        }
 
        /// <summary>
        /// 将应用程序设为或不设为开机启动
        /// </summary>
        /// <param name="onoff">自启开关</param>
        /// <param name="appname">应用程序名</param>
        /// <param name="apppath">应用程序完全路径</param>
        public static bool setautostart(bool onoff, string appname, string apppath)
        {
            bool isok = true;
            //如果从没有设为开机启动设置到要设为开机启动
            if (!isexistkey(appname) && onoff)
            {
                isok = selfrunning(onoff, appname, @apppath);
            }
            //如果从设为开机启动设置到不要设为开机启动
            else if (isexistkey(appname) && !onoff)
            {
                isok = selfrunning(onoff, appname, @apppath);
            }
            return isok;
        }
 
        /// <summary>
        /// 判断注册键值对是否存在,即是否处于开机启动状态
        /// </summary>
        /// <param name="keyname">键值名</param>
        /// <returns></returns>
        private static bool isexistkey(string keyname)
        {
            try
            {
                bool _exist = false;
                registrykey local = registry.localmachine;
                registrykey runs = local.opensubkey(@"software\microsoft\windows\currentversion\run", true);
                if (runs == null)
                {
                    registrykey key2 = local.createsubkey("software");
                    registrykey key3 = key2.createsubkey("microsoft");
                    registrykey key4 = key3.createsubkey("windows");
                    registrykey key5 = key4.createsubkey("currentversion");
                    registrykey key6 = key5.createsubkey("run");
                    runs = key6;
                }
                string[] runsname = runs.getvaluenames();
                foreach (string strname in runsname)
                {
                    if (strname.toupper() == keyname.toupper())
                    {
                        _exist = true;
                        return _exist;
                    }
                }
                return _exist;
 
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// 写入或删除注册表键值对,即设为开机启动或开机不启动
        /// </summary>
        /// <param name="isstart">是否开机启动</param>
        /// <param name="exename">应用程序名</param>
        /// <param name="path">应用程序路径带程序名</param>
        /// <returns></returns>
        private static bool selfrunning(bool isstart, string exename, string path)
        {
            try
            {
                registrykey local = registry.localmachine;
                registrykey key = local.opensubkey(@"software\microsoft\windows\currentversion\run", true);
                if (key == null)
                {
                    local.createsubkey("software//microsoft//windows//currentversion//run");
                }
                //若开机自启动则添加键值对
                if (isstart)
                {
                    key.setvalue(exename, path);
                    key.close();
                }
                else//否则删除键值对
                {
                    string[] keynames = key.getvaluenames();
                    foreach (string keyname in keynames)
                    {
                        if (keyname.toupper() == exename.toupper())
                        {
                            key.deletevalue(exename);
                            key.close();
                        }
                    }
                }
            }
            catch (exception ex)
            {
                string ss = ex.message;
                return false;
                //throw;
            }
 
            return true;
        }

3.如何获取管理员权限请参考

c#如何以管理员身份运行程序 - 酷小孩 - 博客园  https://www.cnblogs.com/babycool/p/3569183.html

c#程序以管理员权限运行 - cosmic_spy - 博客园  https://www.cnblogs.com/interkey/p/runasadmin.html

4.实测稳定可用,希望对你有帮助,谢谢支持。

转载: