您可以使用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");
}
'calc.exe'大概只是初始化在一個單獨的線程的應用程序,然後退出。它不會返回它創建的線程的句柄,因此您無法檢測到窗口關閉。 – 4castle
也許[這個問題](http://stackoverflow.com/q/54686/5743988)將幫助您檢測窗口何時關閉。 – 4castle
你可以添加更多關於你的環境的信息嗎?我可以重現這個問題,但是Rishal dev singh不能。我的環境是Windows 10 Home v。1151,使用Java 1.8.0.910 – 4castle