如何在用户关闭计算器时打印消息?

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

我在 Java 中有一个程序可以用 ProcessBuilder 打开 Windows 计算器。我需要检测程序何时被用户关闭,并显示一条消息说 "Program has been closed successfully".

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

问题是程序打开时出现消息。

您可以使用 this answer 中的代码定期检查进程是否仍在 运行,然后在进程丢失时 post 消息。在 Windows 10,您要查找的进程是 Calculator.exe

这里有一个 Java 8 方法来检查进程是否 运行:

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));
    }

}

然后你可以等待 processIsRunning("Calculator.exe") 为真。

这是一个快速而肮脏的实现:

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");
}