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);
	}
}
相关推荐
剑神一笑2 分钟前
Linux chmod 命令深度解析:从权限位到符号模式的完整指南
linux·运维·chrome
流浪0013 分钟前
LInux系统篇(二):深入剖析 Linux 进程:状态变迁、优先级及调度切换逻辑
linux·运维·服务器
daad7773 分钟前
记录一个串口模块没有回包的问题
linux·运维·服务器
开发者联盟league4 分钟前
在ubuntu上使用apt方式安装gitlab
linux·ubuntu·gitlab
青梅橘子皮8 分钟前
Linux---虚拟地址空间
linux·运维·算法
晚风予卿云月9 分钟前
【Linux】进程控制(一)—进程创建、进程终止与信号全流程详解
linux·运维·服务器·后端开发
skywalk816318 分钟前
在Ubuntu安装明道名部署Playground web网页
linux·运维·ubuntu
爱和冰阔落27 分钟前
Linux/Windows 双平台通关:YOLOv8 目标检测从模型选型到跨平台部署实战
linux·windows·yolo
小蜗牛的路28 分钟前
Linux redhat 7在线安装docker、下载docker依赖、离线安装docker
linux·运维·docker
游戏开发爱好者830 分钟前
Linux 自动上传 App Store Connect:把 IPA 上传流程接进CI工作流
linux·运维·ios·ci/cd·小程序·uni-app·iphone