2

I have a program in Java which opens the Windows calculator with ProcessBuilder. I need to detect when the program is closed by a user, and make a message appear saying "Program has been closed successfully".

Process p = Runtime.getRuntime().exec("calc.exe");
p.waitFor();
System.out.println("Program has been closed successfully");

The problem is the message appears when the program is open.

4castle
  • 28,713
  • 8
  • 60
  • 94
  • `calc.exe` is probably just initializing the application in a separate thread, and then exits. It doesn't return a handle to the thread it creates, so you can't detect the window closing. – 4castle Oct 01 '16 at 19:38
  • Perhaps [this question](http://stackoverflow.com/q/54686/5743988) will help you detect when the window closes. – 4castle Oct 01 '16 at 19:50
  • Can you add more information about your environment? I can reproduce the problem, but Rishal dev singh couldn't. My environment is Windows 10 Home v. 1151, with Java 1.8.0.910 – 4castle Oct 01 '16 at 19:59
  • Windows 10 Pro v. 1607 with Java 1.8.0.101 – Ariishiia Oct 01 '16 at 20:07

1 Answers1

0

You can periodically check if the process is still running using the code from this answer, and then post the message when the process is missing. On Windows 10, the process you're looking for is Calculator.exe.

Here is a Java 8 way to check if the process is running:

private static boolean processIsRunning(String processName) throws IOException {

    String taskList = System.getenv("windir") + "\\system32\\tasklist.exe";
    InputStream is = Runtime.getRuntime().exec(taskList).getInputStream();

    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        return br
            .lines()
            .anyMatch(line -> line.contains(processName));
    }

}

And then you can wait for processIsRunning("Calculator.exe") to be true.

Here's a quick and dirty implementation of that:

public static void main(String[] args) throws Exception {
    Runtime.getRuntime().exec("calc.exe").waitFor();
    while (processIsRunning("Calculator.exe")) {
        Thread.sleep(1000); // make this smaller if you want
    }
    System.out.println("Program has been closed successfully");
}
Community
  • 1
  • 1
4castle
  • 28,713
  • 8
  • 60
  • 94