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

时间:2016-10-01 19:23:02

标签: java processbuilder

我有一个Java程序,用ProcessBuilder打开Windows计算器。我需要检测用户何时关闭该程序,并显示一条消息"程序已成功关闭"。

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

问题是程序打开时会显示消息。

1 个答案:

答案 0 :(得分:0)

您可以使用this answer中的代码定期检查进程是否仍在运行,然后在进程丢失时发布消息。在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");
}