Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

windows - Starting a Java application at startup

I have a Java application.

The application has a setting that decides whether or not the application starts at startup.

Currently, I have it this by placing/removing a shortcut in the StartUp items folder.

However, I am wondering if there is a better way to handle this behaviour.

EDIT

Yes, it's Windows. Sorry for not clearing that before.

The application has an UI where the user may trigger actions, also the application runs a few tasks in the background periodically while running.

@Peter, how could I change the registry with code from within the application? Is that approach compatible with all versions of Windows?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Below is a small example snippet of how it can be done from inside your application

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("

Usage: java SetEnv {key} {value}

");
    
    String key = args[0];
    String value = args[1];
    
    String cmdLine = MessageFormat.format(REG_ADD_CMD, new Object[] { key, value });
    
    Runtime.getRuntime().exec(cmdLine);
}

I'm pretty sure this will work with all versions of Windows since they all use the same StartupRun registry entry.

Hope that helps! :)

Credit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...