c# 注册表开户启动

来源:互联网 发布:如何做淘宝宝贝详情页 编辑:程序博客网 时间:2024/04/27 07:32
 public class StartLaunch
    {
        //表示Window注册表中项级节点,读取 Windows 注册表基项HKEY_LOCAL_MACHINE
        public Microsoft.Win32.RegistryKey loca;
        public Microsoft.Win32.RegistryKey run;
        public bool startflag; 
        public string path = System.IO.Path.GetFullPath("../");//当前应用程序路径的上级目录
        public StartLaunch()
        {
            loca = Microsoft.Win32.Registry.LocalMachine;
            run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            startflag = false;
        }


        public bool isStart()
        {
            //判断开机启动是否注册
            RegistryKey subKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");


            if (subKey.GetValue("Fish") != null)
            {
                //如果注册开机时的应用程序路径与当前的路径不相符则删除
                if (subKey.GetValue("Fish").ToString() != (path + "Fish.exe").ToString())
                {
                    run.DeleteValue("Fish", false);//删除注册,参数一为注册节点名称
                    startflag = false;
                }
                else
                {
                    startflag = true;
                }
            }
            else
            {
                startflag = false;
            }
            subKey.Close();
            return startflag;
        }


        public void RegisteredLaunch()
        {
            if (!isStart())
            {
                try
                {
                    if (File.Exists(path + "Fish.exe"))
                    {
                        run.SetValue("Fish", path + "Fish.exe");//加入注册,参数一为注册节点名称
                        MessageBox.Show("开机自启动成功");
                    }
                   
                }
                catch (Exception)
                {
                    MessageBox.Show("开机自启动失败","警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    loca.Close();
                }


            }
            else
            {
                try
                {
                    run.DeleteValue("Fish",false);//删除注册,参数一为注册节点名称
                    MessageBox.Show("取消自启动成功");
             
                }
                catch (Exception)
                {
                    MessageBox.Show("取消自启动失败", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    loca.Close();
                }


            }
            loca.Close();
        }
    }
原创粉丝点击