Jessica MC Jessica MC - 1 year ago 98
Java Question

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

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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download