How to print a message when a user closes Windows calculator?

83 Views Asked by At

I have a program in java. The program opens Windows calculator with Runtime.exec. So far so good, but I need that when program is closed by a user, a message appears saying "Program has been closed successfully".

I make it with destroy() but that isn't what I need.

2

There are 2 best solutions below

0
On BEST ANSWER

You have to call waitFor() on the Process return by exec(). This will wait for the thread to end, and will return the exit value that you can test (0 is a successful exit value, everything else is an unsuccessful exit value).

try {
    final Process calc = Runtime.getRuntime().exec("calc");
    if (calc.waitFor() == 0) {
        JOptionPane.showMessageDialog(null, "Program has been closed successfully.", "Program closed", JOptionPane.INFORMATION_MESSAGE);
    } else {
        JOptionPane.showMessageDialog(null, "Program has been closed unsuccessfully.", "Program closed", JOptionPane.WARNING_MESSAGE);
    }
} catch (IOException e) {
    JOptionPane.showMessageDialog(null, "IO error: " + e.getMessage(), "Exception encountered", JOptionPane.ERROR_MESSAGE);
} catch (InterruptedException e) {
    JOptionPane.showMessageDialog(null, "Thread interrupted: " + e.getMessage(), "Exception encountered", JOptionPane.ERROR_MESSAGE);
}
1
On

You could try and call waitFor() on the process and when that method returns check isAlive() to be sure. To check whether the process was terminated normally or not you could either examine the return value of waitFor() or call exitValue().