• C# 实现程序开机自启动


    最近在做一个自动备份文件的小工具,需要用到开机自启动

    下面是代码

            private void checkBox8_CheckedChanged(object sender, EventArgs e)
            {
               try
                {
                    //设置开机自启动  
                    if (checkBox8.Checked == true)
                    {
                    /*方法一*/
                    string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
                    //获得文件的当前路径
                    string dir = Directory.GetCurrentDirectory();
                    //获取可执行文件的全部路径
                    string exeDir = dir + @"自动备份.exe.lnk";
                    File.Copy(exeDir, StartupPath + @"自动备份.exe.lnk", true);
                    /*方法二*/
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
                    rk2.SetValue("JcShutdown", path);
                    rk2.Close();
                    rk.Close();
    
                    }
                    //取消开机自启动  
                    else
                    {
                        /*方法一*/
                        string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonStartup);
                        System.IO.File.Delete(StartupPath + @"EcgNetPlug.exe.lnk");
                        /*方法二*/
                        string path = Application.ExecutablePath;
                        RegistryKey rk = Registry.LocalMachine;
                        RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
                        rk2.DeleteValue("JcShutdown", false);
                        rk2.Close();
                        rk.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

    第一种方法原理是直接把可执行文件的快捷方式复制到系统的启动目录里,这种方式不会被安全软件拦截,不需要额外的权限

    第二种方式是直接写注册表,这种方式可能会把安全软件拦截

    大家可以自己试试,有问题可以留言,我也是边学边做

    作者:逐梦
    出处:http://www.cnblogs.com/huanjun/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利

  • 相关阅读:
    应用中心无法访问时后台插件列表访问慢的优化
    HTML5 地理定位 【来自百度应用分享平台】
    快捷键补充
    进击的雨燕------------在导航上的UISearchController实现动画效果
    iOS -------- 应用程序引用系统通讯录
    字典和JSON格式字符串相互转换
    进击的雨燕--------------------Swift ? !
    Objective-C多继承的实现
    进击的雨燕------------iOS8中UIAlertController
    进击的雨燕-------------------高级运算符
  • 原文地址:https://www.cnblogs.com/huanjun/p/8438284.html
Copyright © 2020-2023  润新知