C# winform设置开机启动

C# winform设置开机启动

命名空间

using Microsoft.Win32;

代码

注意this.uiCheckBox1.Checked时针对Winfom程序的,如果是命令行程序要另外设置一个触发值

private void cbx_startup()
{
    // 要设置软件名称,有唯一性要求,最好起特别一些
    string SoftWare = "SunnyNetEaseCloud";
    
    // 注意this.uiCheckBox1.Checked时针对Winfom程序的,如果是命令行程序要另外设置一个触发值
    if (this.uiCheckBox1.Checked)
    {

        Console.WriteLine("设置开机自启动,需要修改注册表", "提示");
        string path = Application.ExecutablePath;
        RegistryKey rk = Registry.CurrentUser; //
        // 添加到 当前登陆用户的 注册表启动项     
        try
        {
            //  
            //SetValue:存储值的名称   
            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");

            // 检测是否之前有设置自启动了,如果设置了,就看值是否一样
            string old_path = (string)rk2.GetValue(SoftWare);
            Console.WriteLine("\r\n注册表值: {0}", old_path);
            
            if (old_path ==null || !path.Equals(old_path))
            {
                rk2.SetValue(SoftWare, path);
                 Console.WriteLine("添加开启启动成功");
            }

            rk2.Close();
            rk.Close();

        }
        catch (Exception ee)
        {
             Console.WriteLine("开机自启动设置失败");

        }
    }
    else
    {
        // 取消开机自启动
        Console.WriteLine("取消开机自启动,需要修改注册表", "提示");
        string path = Application.ExecutablePath;
        RegistryKey rk = Registry.CurrentUser;
        try
        {
            // SetValue: 存储值的名称
            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            
            string old_path = (string)rk2.GetValue(SoftWare);
            Console.WriteLine("\r\n注册表值: {0}", old_path);

            rk2.DeleteValue(SoftWare, false);
            Console.WriteLine("取消开启启动成功");
            rk2.Close();
            rk.Close();
        }
        catch (Exception ee)
        {
            //MessageBox.Show(ee.Message.ToString(), "提 示", MessageBoxButtons.OK, MessageBoxIcon.Error);  // 提示
             Console.WriteLine("取消开机自启动失败");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值