Ariishiia Ariishiia - 2 months ago 11
Java Question

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

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.

Answer

You can use finally block to handle that scenario, Added code for more clarification.

Runtime rt = Runtime.getRuntime();
    try {
        Process proc = rt.exec("notepad");
        int exitVal = proc.waitFor();
        System.out.println("Process exitValue: " + exitVal);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        System.out.println("Closed");
    }
Comments