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);
	}
}
相关推荐
CSDN121101 小时前
麒麟 V10 安装 Node-RED、IEC 104 协议插件及界面汉化
linux·编辑器·vim
不会代码的小猴1 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
沫璃染墨2 小时前
《Qt从零入门系列(六):信号与槽进阶——从多种连接方式到Lambda表达式》
开发语言·c++·qt·代码规范·设计规范·qt5
晨枫阳2 小时前
@changesets/cli是什么?哪些情况下需要使用?怎么使用
linux·运维·ubuntu
不会就选b3 小时前
Linux之网络基础(二)
linux·运维·网络
莫浅子4 小时前
Day 4:USB 2.0 时序与带宽预算
linux·运维·网络
ly76894 小时前
Linux 从入门到实践:系统架构、常用命令、服务管理与故障排查详解
linux·运维·系统架构
2401_868534785 小时前
在企业环境中快速安装配置 FreeBSD Unix 服务器操作系
linux·网络协议
小雪崩5 小时前
嵌入式学习 day27:标准IO
linux·c语言·学习
Arnold.Shen5 小时前
Dell Storage SC - 如何发送SupportAssist,并启用安全控制台
linux·安全