C# 设置Winform开机运行

来源:互联网 发布:淘宝拍单兼职真假 编辑:程序博客网 时间:2024/06/06 14:00
using Microsoft.Win32; #region 设置程序开机运行        // <summary>        /// 设置程序开机运行        /// </summary>        /// <param name="fileName">要运行的EXE程序名称</param>        /// <param name="isAutoRun">是否开机运行</param>        private void SetAutoRun(string fileName, bool isAutoRun)        {            RegistryKey reg = null;            try            {                if (!System.IO.File.Exists(fileName))                {                    throw new Exception("该文件不存在!");                }                String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);                if (reg == null) //如果该项不存在,则创建该子项                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");                if (isAutoRun)                    reg.SetValue(name, fileName);                else                    reg.SetValue(name, false);            }            catch            {                throw; // new Exception(ex.ToString());               }            finally            {                if (reg != null)                    reg.Close();            }        }        #endregion