开机自启动简明代码实现

2019-05-14  本文已影响0人  田陌允
剧照

不废话了,直接上代码

    autoStartWidget = new QWidget(this);
    label_autoStart = new QLabel(autoStartWidget);
    label_autoStart->setText(tr("Auto Start:"));
    label_autoStart->setObjectName(QStringLiteral("label_autoStart"));
    label_autoStart->setGeometry(QRect(20 * m_factorX, 25 * m_factorY, 80 * m_factorX, 25 * m_factorY));
    switchBtn = new SwitchButton(autoStartWidget);
    switchBtn->setButtonStyle(SwitchButton::ButtonStyle_CircleIn);
    switchBtn->setObjectName(QStringLiteral("switchBtn"));
    switchBtn->setGeometry(QRect(150 * m_factorX, 25 * m_factorY, 50 * m_factorX, 25 * m_factorY));
    switchBtn->setChecked(pref->bIsAutoRun);//读取ini
    connect(switchBtn, SIGNAL(checkedChanged(bool)), this, SLOT(autoStart(bool)));

槽函数:

/**
 * @brief SystemSettingConfig::autoStart 开机自启动
 * @param f
 */
void SystemSettingConfig::autoStart(bool f)
{
    if(pref->bIsAutoRun == f)
        return;
    if(!AutoRunWithSystem(f))
    {
        switchBtn->setChecked(pref->bIsAutoRun);
        return;
    }
}

//设置为开机启动
static bool AutoRunWithSystem(bool IsAutoRun)
{
    QSettings *reg = new QSettings(
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
        QSettings::NativeFormat);

    QString Path = QApplication::applicationFilePath();
    QString Name = QApplication::applicationName();

    if (IsAutoRun) {
        reg->setValue(Name, Path.replace("/","\\"));
    } else {
        reg->setValue(Name, "");
    }

    bool ret = true;
    if(reg->status() != QSettings::NoError)
    {
        ret = false;
    }
    delete reg;
    return ret;
}
上一篇 下一篇

猜你喜欢

热点阅读