系统启动时自动启动程序

来源:互联网 发布:华为停用移动数据 编辑:程序博客网 时间:2024/05/23 11:35

下面主要介绍采用编辑注册表的方式来实现。一般系统启动时自动启动程序的注册信息都在“SOFTWARE/Microsoft/Windows/CurrentVersion/Run”里面。

 /// <summary>
        /// 系统启动时自动启动
        /// </summary>
        /// <param name="fileName">自动打开的文件,如果是可执行应用程序,即为程序的路径及文件名(带后缀)</param>
        /// <param name="isAutoRun">是否自动启动,true表示自动启动,false表示不自动启动</param>
        private void SetAutoRun(string fileName, bool isAutoRun)
        {
            Microsoft.Win32.RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                String name = fileName.Substring(fileName.LastIndexOf(@"/") + 1);
                reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run", true);
                if (reg == null)
                    reg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
                if (isAutoRun)
                    reg.SetValue(name, fileName);
                else
                    reg.SetValue(name, false);               
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

原创粉丝点击