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);
	}
}
相关推荐
郝学胜_神的一滴3 小时前
Qt 高级开发 030:QListWidget 右键菜单全解,从策略配置到精准删除的优雅实现
c++·qt
Championship.23.243 小时前
Linux 3.0 音频机制深度解析:ALSA基础架构与传统音频驱动模型
linux·运维·音视频·alsa
海天鹰3 小时前
图片去黑边算法
qt·算法
Tian_Hang3 小时前
Linux基础知识(四)
linux·ide·驱动开发·计算机视觉·硬件工程·动画
HLC++4 小时前
Linux文件操作
linux·运维·服务器
晚风予卿云月4 小时前
【Linux】进程控制(二)——进程等待 全方位详解
linux·运维·服务器·进程控制·进程等待
上天_去_做颗惺星 EVE_BLUE4 小时前
【新 Linux 服务器上手全攻略】系统巡检、存储规划与开发环境初始化
linux·运维·服务器·ubuntu·macos·centos
REDcker4 小时前
WWDC2026系统更新综述
macos·ios·开发者·apple·wwdc·ipados·wwdc2026
Titan20244 小时前
Linux文件系统
linux·服务器
c238564 小时前
linux文件权限深入了解(下)
linux·运维·服务器