一、代码
#include <QtCore/QCoreApplication> #include <QtCore/QSettings> #include <QtCore/QDebug> #include <QtCore/QProcess> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // 获取当前程序的路径 QString appPath = QCoreApplication::applicationFilePath(); appPath.replace("/", "\\"); appPath = "\"" + appPath + "\""; // 设置开机自启动 QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); settings.setValue("MyApp", QVariant(appPath)); // 查看是否设置成功 qDebug() << "Is auto start enabled?" << settings.contains("MyApp"); // 取消开机自启动 settings.remove("MyApp"); // 查看是否取消成功 qDebug() << "Is auto start disabled?" << !settings.contains("MyApp"); }
二、注意
设置的启动项路径字符串需包含双引号 “ ” ,否则无效、开机无法自启动!!!
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/VsFMs