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);
	}
}
相关推荐
雨疏风骤12407 小时前
ROM与RAM,储存地址、链接地址以及运行地址
linux·stm32·嵌入式·linux嵌入式
fy zs8 小时前
网络基础概念
linux·网络·c++
学习3人组8 小时前
CentOS 系统下 ModelScope 模型下载的默认目录
linux·python·centos
不会c嘎嘎8 小时前
QT中的常用控件 (三)
开发语言·qt
闫有尽意无琼8 小时前
Qt局部变量“遮蔽(shadow)”成员变量导致lambda传参报错
开发语言·qt
寻找华年的锦瑟8 小时前
Qt-YOLO-OpenCV
qt·opencv·yolo
南桥几晴秋8 小时前
Qt显示类控件
开发语言·c++·qt
centor8 小时前
国际版 UnitySetup-Android-Support 安装 Mac 设备
android·macos
_OP_CHEN8 小时前
【从零开始的Qt开发指南】(十八)Qt 事件进阶:定时器、事件分发器与事件过滤器的实战宝典
qt·前端开发·事件过滤器·qt事件·gui开发·qt定时器·事件分发器
晨风先生8 小时前
打包Qt程序的脚本package.bat
开发语言·qt