Search code examples
javawindowsstartup

Application start on logon with Java


So my question today is one of personal academic willingness to learn, despite it probably being a little beyond my level. Bear with me on this!

I've made a simple application, that might look (and might BE) a little clunky. All it does is open a window, and have you press a button, to close said window.

Here's the code for this questionable construct:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class StartupLearning extends JFrame implements ActionListener {

private JButton button;

public StartupLearning() {

    super("If you see this box on startup, you've learned something new today!");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    button = new JButton("Close this box");
    button.addActionListener(this);
    button.setActionCommand("Close");
    add(button);
    pack();

}

@Override
public void actionPerformed(ActionEvent e) {

    String cmd = e.getActionCommand();

    if (cmd.equals("Close"))
        dispose();
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new StartupLearning().setSize(400, 75);
        }

    });
}
}

I know it's not perfect, and I know it probably has faults that could be optimized and organized, but like mentioned, this is just me trying to teach myself something new.

Now, what I wonder about is what code I can use, and how I can use said code to make this one very simple application run when a user logs in to Windows (let's leave cross-platform out of it, if it makes things even more complicated)?

For someone about as green as he sounds, what class or code would best suit this job, and how can I use it with my presented code?

All that needs to happen, is that this simple code needs to run when the user is logged in, and close when the user hits the button.

EDIT

Thanks to you three who answered, and I have clearly not been specific enough. I need my little pretty code to run on login without any user input or moving of the file.

The application needs to be able to run on start up right after the user has launched it once.

Meaning that I'd run the app, and from now on, it will always run on start up, until I delete the application or tell it in the source that it will no longer do so.

EDIT2

You guys are awesome for bearing with me this long. To further clarify:

Assume the user is the administrator, and there is no password or any form of protection is being used. No anti-virus or anti-spyware or firewall or anything. No defenses at all.

Assume the .jar file and .class file are both in C:\.

Assume the application will be run once manually, before a start-at-login is expected to happen. This is when the application gets its chance to add itself to the registry or put a .bat in the startup folder or something.

Don't worry so much about the ethics, as I'm just trying to establish how a simple Java app can start itself in the every time I reboot.

Could I perhaps have the application put a shortcut of itself in the startup folder or something?

Or could I have it add itself to the registry after the user runs the app?

I know I'm asking a lot, but could I have a demonstration of something like this?

You guys are my heroes.


Solution

  • Run At Login (manually)

    Once you packaged your app, you can just put java -jar your-app.jar in a .bat file in the Windows startup menu.

    If you don't want to create a jar (e.g. because your app is simple enough) and always assuming you have your Java environment variables configured (JAVA_HOME, PATH....), you can just run directly your bytecode:

    startup.bat:

    cd your/app/bytecode/path
    java yourapp
    

    See here how to start an app at startup.

    Run at Startup (manually)

    If you need the application to run before the user login you can use the Windows Task Scheduler, and use the trigger at startup, wrapping your application as described in this OS answer:

    @echo off
    REM Eventually change directory to the program directory 
    cd C:\Users\User1\Documents\NetBeansProjects\Facebook\dist\
    REM run the program
    "C:\Program Files\Java\jdk1.7.0\bin\java.exe" -jar "C:\Users\User1\Documents\NetBeansProjects\Facebook\dist\Facebook.jar"
    

    Run at Startup (installer)

    In case you really don't want any user interaction the only easy (and IMHO ethic) solution I imagine is the Installer.

    You basically need a wizard installing your application for you (and for the user) configuring it to run at startup. There are many wizards, you can build your own or start your research having a look here.

    Run at Startup (standalone)

    Use the approach described here, writing something like this directly in your small application (original post here):

    static final String REG_ADD_CMD = "cmd /c reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /v \"{0}\" /d \"{1}\" /t REG_EXPAND_SZ";
    private void exec(String[] args) throws Exception
    {
        if (args.length != 2)
            throw new IllegalArgumentException("\n\nUsage: java SetEnv {key} {value}\n\n");
    
        String key = args[0];
        String value = args[1];
    
        String cmdLine = MessageFormat.format(REG_ADD_CMD, new Object[] { key, value });
    
        Runtime.getRuntime().exec(cmdLine);
    }
    

    Key is your app name (not relevant), Value is your jar file or the .bat command that runs your application (see above methods on how to package a jar or run a .class inside a .bat file), e.g. "C:\Users\YourApp.jar"

    NOTE

    As stated by the author, this approach should work with any versions of Windows, since they all use the same Startup\Run registry entry. Though, keep in mind that this is not portable and you have probably to tune the script according to the MS OS version.

    NOTE 2

    Think twice before modifying the registry code directly from your application (the hacky way). For doing that you probably need Supervisor/Admin priviledges every time the application runs. Moreover doing that without correct, explicit user prompt can be seen as a malware/spam malicious practice.