使程序开机自启

Posted on 2019-01-27 23:12  努力成长静待花开  阅读(147)  评论(0编辑  收藏  举报

实现效果:

     

知识运用:

  注册表项:[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] 下的键值对

实现代码:

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                string pro = textBox1.Text.Trim();
                string proName = textBox1.Text.Substring(pro.LastIndexOf("\\")+1);  //获取文件名
                RegistryKey rk=Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);
                if (rk ==null)                                                      //如果指定项不存在
                    rk = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                rk.SetValue(proName,pro);
                if (MessageBox.Show("设置成功!") == DialogResult.OK)
                    RefreshSystem();                                               //刷新系统
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                try
                {
                    string pro = textBox1.Text.Trim();
                    string proName = textBox1.Text.Substring(pro.LastIndexOf("\\") + 1);  //获取文件名
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                    if (rk == null)                                                      //如果指定项不存在
                        rk = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    rk.DeleteValue(proName);
                    if (MessageBox.Show("设置成功!") == DialogResult.OK)
                        RefreshSystem(); 
                }
                catch{}                                              
            }
        }