Question

I'm working on a (non-malicious) screen-locking sort of Swing application, and I've adapted code from Martijn Courteaux's answer at Use Java to lock a screen to do this. The problem is that when I use Runtime.getRuntime().exec("explorer.exe"); to reopen the Explorer process at program closing, Netbeans thinks that my project is still running because the resulting explorer.exe is running. CMD prompt and JCreator don't have this issue.

Can anyone give an example of the preferred way to call a command like explorer.exe to avoid this happening with Netbeans?

Edit: I close the Explorer process at the start of the program (which includes the taskbar). When I run Explorer, it's not to open a Windows Explorer window (which works totally fine with the given answers) but to restore the regular Windows UI.

Was it helpful?

Solution

The problem is Runtime@exec is waiting for the child process to exit. This is the default behavior.

If you want to execute a parentless process (a process in which the parent process can terminate even though the child is still running), you need to get a little more creative.

We use...

"cmd /C start /B /NORMAL " + yourCommand

I would highlight recommend using ProcessBuilder as it makes it significantly easier to build and execute external commands.

Something like...

ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "start", "/B", "/NORMAL", "explorer.exe");
pb.start();

For example....

nb I run this is NetBeans and the program exited after/as explorer opened.

There is one little draw back. This doesn't like long file names. You'll need to find some way to produce short file names/paths for this to work. I was forced to use JNI solution for this

OTHER TIPS

ProcessBuilder allows you to create and control processes.

Here's some example code, it's fairly complex but I don't have time to dumb it down (no offense): https://github.com/Xabster/Botster/blob/master/src/commands/ExecCommand.java

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top