Answer the question
In order to leave comments, you need to log in
How can a Java application add itself to windows startup?
I tried different ways, for example through the registry:
String REG_ADD_CMD = "cmd /c reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /v \"AppName\" /d \"%PROGRAMFILES%\\AppPath\App.exe\" /t REG_SZ";
Runtime.getRuntime().exec(REG_ADD_CMD);
public void setStartup(boolean startup) {
if (System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0) {
// автозапуск для Mac OS X
String plist_text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
plist_text += "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDsPropertyList-1.0.dtd\">\n";
plist_text += "<plist version=\"1.0\">\n";
plist_text += " <dict>\n";
plist_text += " <key>Label</key>\n";
plist_text += " <string>ru.sp.MySquperApp</string>\n";
plist_text += " <key>ProgramArguments</key>\n";
plist_text += " <array>\n";
plist_text += " <string>/usr/bin/open</string>\n";
plist_text += " <string>/Applications/ChatMySquperApp</string>\n";
plist_text += " </array>\n";
plist_text += " <key>RunAtLoad</key>\n";
plist_text += " <true/>\n";
plist_text += " </dict>\n";
plist_text += "</plist>";
File plist = new File(System.getProperty("user.home")
+ "/Library/LaunchAgents/ru.sp.MySquperApp.plist");
if (startup) {
FileWriter writeFile = null;
try {
writeFile = new FileWriter(plist);
writeFile.write(plist_text);
} catch (IOException e) {
log.fatal(e);
} finally {
if (writeFile != null) {
try {
writeFile.close();
} catch (IOException e) {
log.fatal(e);
}
}
}
} else {
if (plist.exists()) {
plist.delete();
}
}
}else{
// для виндовса
String s = "";;
if(startup){
s = "cmd /C reg add HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v " +
"MySquperApp /t REG_SZ /d \"%PROGRAMFILES%\\MySquperApp\\MySquperApp.lnk\" /f";
}else{
s = "cmd /C reg delete HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run " +
"/v MySquperApp /f\r\n";
}
try {
Runtime.getRuntime().exec(s);
} catch (IOException e) {
log.fatal(e,e);
}
}
}
Answer the question
In order to leave comments, you need to log in
On Windows 8, writing to "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" needs privilege escalation, hence the error. Alternatively, write to "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\", the application will automatically start only under the user under which it was written. Or elevate privileges to write to "HKEY_LOCAL_MACHINE" (application will run under all users).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question