程序开机自启

2 篇文章 0 订阅
Try
        '程序开机启动
        My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run",
                                      IO.Path.GetFileName(Application.ExecutablePath),
                                      Application.StartupPath & "\" & IO.Path.GetFileName(Application.ExecutablePath))
    Catch ex As Exception
    End Try

判断程序是否已经运行
Process[] _processes = Process.GetProcessesByName(“Hello”);hello exe文件
if ( _processes.Length > 1 )
{
Application.Exit();
}

C#==
Registry.SetValue(“HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run”,
System.IO.Path.GetFileName(Application.ExecutablePath), Application.StartupPath + “\” + System.IO.Path.GetFileName(Application.ExecutablePath));

win10需要设置管理员模式运行 项目右键-属性-安全性 生成 app.manifest文件 更改

    /// <summary>  
    /// 更改是否开机自启动
    /// </summary>  
    /// <param name="isAutoStartup">是否开机自启动</param>  
    public static void ChangeAutoStartUp(bool isAutoStartup)
    {
        string executablePath = Application.ExecutablePath; //可执行文件路径
        string programName = Path.GetFileNameWithoutExtension(executablePath); //程序名称
        //自启动注册表路径
        string registryRunPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        try
        {
            bool isAdmin = IsAdmin();
            //判断当前用户是否是管理员
            RegistryKey registryKey = isAdmin
                ? Registry.LocalMachine.CreateSubKey(registryRunPath)
                : Registry.CurrentUser.CreateSubKey(registryRunPath);
            if (registryKey == null) return;
            if (isAutoStartup)
            {
                registryKey.SetValue(programName, executablePath); //开启自启动
            }
            else
            {
                registryKey.DeleteValue(programName, false); //关闭自启动
            }
        }
        catch (Exception e)
        {
            //捕获异常;
        }
    }

    /// <summary>
    /// 判断程序是否以管理员身份运行
    /// </summary>
    /// <returns></returns>
    private static bool IsAdmin()
    {
        bool result = false;
        try
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            result = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
        catch (Exception e)
        {
            //捕获异常;
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值