C#.NET Form设置/取消开机自动运行

创建于 2014-12-15

迁移自个人的百度空间

------------------------------

1、在Form_Load触发事件里加入如下代码

// 判断程序是否已经设置成开机自动启动

RegistryKey local_chek = Registry.LocalMachine;

RegistryKey run_Check = local_chek.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

if (run_Check.GetValue("RobotPC").ToString().ToLower() != "false")

{

    this.chkBoxAutoRun.Checked = true;

}

else

{

    this.chkBoxAutoRun.Checked = false;

}

2、添加chkBoxAutoRun复选框,并在其触发事件中实现如下代码

// 开机自动运行

private void AutoRun()

{

    try

    {

        //获取程序执行路径..

        string starupPath = Application.ExecutablePath;

        //class Micosoft.Win32.RegistryKey. 表示Window注册表中项级节点,此类是注册表装.

        RegistryKey local = Registry.LocalMachine;

        RegistryKey run = local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

             

        //SetValue:存储值的名称

        if (gbAutoRun == false)

        {

            run.SetValue("RobotPC", false);     // 取消开机运行

        }

        else

        {

            run.SetValue("RobotPC", starupPath);   // 设置开机运行

        }

 

        local.Close();

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message,

                        "错误",

                        MessageBoxButtons.OK,

                        MessageBoxIcon.Exclamation);

    }

}

 

private void chkBoxAutoRun_CheckedChanged(object sender, EventArgs e)

{

    gbAutoRun = this.chkBoxAutoRun.Checked;  // gbAutoRub是全局变量

    AutoRun();

}

猜你喜欢

转载自blog.csdn.net/LinSeeker85/article/details/88884543