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);
	}
}
相关推荐
砚凝霜6 分钟前
【软考信息安全】第十九章 Unix/Linux安全分析与防护
linux·安全·unix
creator_Li36 分钟前
Linux 的 Page Cache
linux·page cache
好好学习O(∩_∩)O1 小时前
[QT] 多线程moveToThread 和易踩的8个坑
开发语言·qt
KING-WU5122 小时前
Linux GDB 调试实战指南:从编译到断点调试
linux·运维·服务器
Lucis__2 小时前
深入理解程序链接与加载—从动静态链接到库加载
linux·elf·链接·程序·动静态库
影视飓风TIM3 小时前
Linux 进程信号原理与剖析
linux·运维·服务器
缘友一世3 小时前
开源 Linux截图工具闪构(SnapForge)
linux·运维·ubuntu·开源·截图
北i3 小时前
Dubbo 默认超时重试:把下游打雪崩的隐形放大器
开发语言·qt·dubbo
朱包林4 小时前
iTerm2终端配置指南
linux·javascript·python·云原生·容器·kubernetes·云计算
祖力554 小时前
Linux系统移植、烧录与环境的搭建
linux·运维·服务器