代码之家  ›  专栏  ›  技术社区  ›  Ariishiia

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

  •  2
  • Ariishiia  · 技术社区  · 8 年前

    我有一个Java程序,它用 ProcessBuilder 。我需要检测程序何时被用户关闭,并显示消息“程序已成功关闭”。

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

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   Community frankie liuzzi    7 年前

    您可以使用中的代码定期检查进程是否仍在运行 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");
    }