Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add/Remove Java desktop application to Windows Startup programmatically in Java?

I have a windows desktop application written on Java. I have a checkbox there saying "Launch at system startup". So if this checkbox is checked then I want the app to start when a user logs in to Windows. And if it's not checked then I want to remove it (If it already exists).

And I want to do it from my application using Java (I know there are some other methods like batch file and windows service).

I have checked Stack Overflow code but it didn't work. Actually I just want a solution like Code Project.

But unfortunately it's in C# .net. So how can I achieve this using Java?

EDIT: I am also open for JNA/JNI approach. The thing is I just need to do it in Java. And it doesn't matter whatever I am using. I am ready to go for JNA/JNI.

like image 559
Partho Biswas Avatar asked Oct 21 '25 16:10

Partho Biswas


1 Answers

Another option which is much simpeler than a COM solution is to add/remove a file to one of the Windows startup folders. You could do something like this:

    String allUsersStartupFolder = "C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Startup";
    //String personalStartupFolder = "C:/Users/" + System.getProperty("user.name") + "/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup";

    File startupFolder = new File(allUsersStartupFolder);
    System.out.println(startupFolder);
    File startupFile = new File(startupFolder, "MyProgramStartup.bat");

    if(startupFile.exists()){
        System.out.println("Unregister");
        startupFile.delete();
    }else{
        System.out.println("Register");
        Files.write(startupFile.toPath(), "java -jar MyProgram.jar".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }
like image 57
HELOX Avatar answered Oct 23 '25 05:10

HELOX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!