Qt在Win,Mac和Linux的开机自启设置

Windows

Windows 使用注册表来管理开机自启的应用程序。

cpp 复制代码
void runWithSystem(const QString& name, const QString& path, bool autoRun) {
	QSetting reg("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSetting::NativeFormat);
	reg.setValue(name, autoRun ? path : "");
}

Linux

Linux 使用 ~/.config/autostart/*.desktop 来管理开机自启的应用程序。

cpp 复制代码
void runWithSystem(const QString& name, const QString& path, bool autoRun) {
	QString desktopFilePath = QStandarPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config/autostart" + name + ".desktop";
	if (autoRun) {
		QFile file(desktopFilePath);
		if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
			QTextStream out(&file);
			out << "[Desktop Entry]\n"
				<< "Type=Application\n"
				<< "Name=" << name << "\n"
				<< "Exec=" << path << "\n"
				<< "X-GNOME-Autostart-enabled=true";
			file.close();
		}
	}
	else {
		QFile::remove(desktopFilePath);
	}
}

Macos

Macos 采用 launchd 来管理启动项。

cpp 复制代码
void runWithSystem(const QString& name, const QString& path, bool autoRun) {
	QString plistPath = QStandardPaths::writableLocation(QStandards::HomeLocation) + "/Library/LaunchAgents/" + name + ".plist";
	if (autoRun) {
		QFile file(plistPath);
		if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
			QTextStream out(&file);
			out << "<?xml version\"1.0\" encoding=\"UTF-8\"?>\n"
					"!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"\n"
					"	\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
					"<plist version=\"1.0\">\n"
					"<dict>\n"
					"	<key>Label</key>\n"
					"	<string>" << name << "</string>\n"
					"	<key>ProgramArguments</key>\n"
					"	<array>\n"
					"		<string>" << path << "</string>\n"
					"	</array>\n"
					"	<key>RunAtLoad</key>\n"
					"	<true/>\n"
					"</dict>\n"
					"</plist>";
			file.close();
		}
	}
	else {
		QFile::remove(plistPatch);
	}
}
相关推荐
鱼很腾apoc7 分钟前
【Redis】第4期 详解主从复制、哨兵、集群
linux·redis·学习·集群·主从复制·哨兵
老一岁12 分钟前
Git详解_提交_回退_分支_合并
大数据·linux·git
ai_xiaogui22 分钟前
Ubuntu Server 安装避坑实录:服务器装成桌面版、网卡驱动缺失怎么办?
linux·服务器·ubuntu·ubuntu server·ubuntu 网卡驱动安装·服务器装机避坑·服务器装机
小则又沐风a29 分钟前
线程的互斥和同步
linux·c++
开发者导航36 分钟前
Cursor plugins 插件仓库上手:结构解析与安装使用教程
android·linux·ubuntu·ai·typescript·cursor·插件开发
飞花漫卷,情随岁迁43 分钟前
命令进阶与 Playbook 快速入门
java·linux·运维·服务器·网络·数据库·智能路由器
master3361 小时前
Linux 内核参数详解:原理、调优与生产实践
linux·运维·服务器
MSTcheng.1 小时前
【LinuxIO篇】Linux学习第二十四弹——Linux学习第二十四弹——为什么 fork 后多了 3 条输出?两层缓冲区彻底讲透!
linux·运维·学习
余额瞒着我当琳1 小时前
Linux 软件管理实战:yum 包管理器、vim 编辑器与 gcc 编译流程
linux·编辑器·vim
lgbisha2 小时前
银河麒麟:软链接还在却打不开,怎么查它指向了哪里
linux·服务器·前端·银河麒麟