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);
	}
}
相关推荐
CriticalThinking6 小时前
在xshell中使用ssh隧道访问远程服务
linux·网络·ssh
爱装代码的小瓶子6 小时前
安工大题目分类(含解析和翻译)
linux·网络·c
大智兄6 小时前
128.配置qt(交叉)编译的路径---解决无法编译的问题
qt
是个西兰花7 小时前
linux:命名管道与共享内存
linux·运维·服务器·网络·c++
Snasph7 小时前
Linux 日志流水线深度解析:syslog() → journald → rsyslog → /var/log/syslog
linux·syslog·rsyslog
凡人叶枫7 小时前
Effective C++ 条款08:别让异常逃离析构函数
java·linux·数据库·c++·嵌入式开发
新时代牛马7 小时前
内核调试方法
linux·学习
墨痕诉清风7 小时前
Linux系统设置上海时间(24小时制)
linux·运维·服务器
utf8mb4安全女神7 小时前
脚本模块化
linux·运维·服务器
daad7778 小时前
纪录无人机PID参数配置
linux