Last active
February 17, 2023 04:57
-
-
Save andreybutov/33783bca1af9db8f9f36c463c77d7a86 to your computer and use it in GitHub Desktop.
How do I make my Qt app start automatically at login?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// How do I make my Qt app start automatically at login? | |
// This solution is for Windows and Mac. It was tested with Qt 5.5. | |
// | |
// - Andrey Butov ( andreybutov.com ) | |
// | |
void setAppToStartAutomatically ( bool startAutomatically ) | |
{ | |
#if defined ( Q_OS_MAC ) | |
// Remove any existing login entry for this app first, in case there was one | |
// from a previous installation, that may be under a different launch path. | |
{ | |
QStringList args; | |
args << "-e tell application \"System Events\" to delete login item\"" | |
+ macOSXAppBundleName() + "\""; | |
QProcess::execute("osascript", args); | |
} | |
// Now install the login item, if needed. | |
if ( startAutomatically ) | |
{ | |
QStringList args; | |
args << "-e tell application \"System Events\" to make login item at end " + | |
"with properties {path:\"" + macOSXAppBundlePath() + "\", hidden:false}"; | |
QProcess::execute("osascript", args); | |
} | |
#elif defined ( Q_OS_WIN ) | |
QString key = "YouApplicationName"; | |
QSettings registrySettings( | |
"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", | |
QSettings::NativeFormat); | |
registrySettings.remove(key); | |
if ( startAutomatically ) { | |
registrySettings.setValue(key, QString("\"" + windowsAppPath() + "\"")); | |
} | |
registrySettings.sync(); | |
#endif | |
} | |
QString macOSXAppBundlePath() | |
{ | |
#ifdef Q_OS_MAC | |
QDir dir = QDir ( QCoreApplication::applicationDirPath() ); | |
dir.cdUp(); | |
dir.cdUp(); | |
QString absolutePath = dir.absolutePath(); | |
// absolutePath will contain a "/" at the end, | |
// but we want the clean path to the .app bundle | |
if ( absolutePath.length() > 0 && absolutePath.right(1) == "/" ) { | |
absolutePath.chop(1); | |
} | |
return absolutePath; | |
#else | |
return ""; | |
#endif | |
} | |
QString macOSXAppBundleName() | |
{ | |
#ifdef Q_OS_MAC | |
QString bundlePath = macOSXAppBundlePath(); | |
QFileInfo fileInfo(bundlePath); | |
return fileInfo.baseName(); | |
#else | |
return ""; | |
#endif | |
} | |
QString windowsAppPath() | |
{ | |
#ifdef Q_OS_WIN | |
return QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); | |
#else | |
return ""; | |
#endif | |
} |
Hi, Thank you for your code.
Btw, I have some issue to run your code....
If possible, could you post real project(.pro) for me to run easily?
Thank you again.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@DracFiendMG It's a static method on QCodeApplication.