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);
	}
}
相关推荐
脚踏实地,坚持不懈!1 分钟前
Linux 6.18.7 内存分配与回收 —— 代码梳理
linux·运维·网络
byte轻骑兵2 分钟前
【BlueZ 】hci 模块:用户态 HCI 层的核心封装与消息处理
linux·人工智能·bluez·电脑蓝牙·嵌入式蓝牙
Android系统攻城狮1 小时前
Linux Gstreamer深度解析之gst_audio_format_build_integer调用流程与实战(十二)
linux·运维·服务器·音视频·车载音视频·gstreamer进阶
吴声子夜歌2 小时前
Shell脚本——流程控制:for循环
linux·运维·shell
事圆则缓2 小时前
Ubuntu 安装与配置 Samba 服务器
linux·服务器·ubuntu
GeW2 小时前
每天2小时,21天闭环计划-RHCE通关时间表全公开
linux
weixin_450813533 小时前
pdf文档转为markdown文档
linux·pdf
我的小卷呀4 小时前
Linux ip 命令底层逻辑与实战指南
linux·运维·c语言·网络协议·tcp/ip·网络安全
handler014 小时前
【Linux】ELF、链接与动态库,程序装载全解析
linux·运维·服务器·chrome·c·elf·文件
dishugj4 小时前
操作系统四大特征|软考架构师考点梳理
java·linux·服务器