How to get a list of current open windows/process with Java?

后端 未结 14 1332
抹茶落季
抹茶落季 2020-11-22 05:20

Does any one know how do I get the current open windows or process of a local machine using Java?

What I\'m trying to do is: list the current open task, windows or

相关标签:
14条回答
  • 2020-11-22 05:57

    This might be useful for apps with a bundled JRE: I scan for the folder name that i'm running the application from: so if you're application is executing from:

    C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe
    

    then you can find if it's already running in J9, by:

    public static void main(String[] args) {
        AtomicBoolean isRunning = new AtomicBoolean(false);
        ProcessHandle.allProcesses()
                .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp"))
                .forEach((process) -> {
                    isRunning.set(true);
                });
        if (isRunning.get()) System.out.println("SomeJavaApp is running already");
    }
    
    0 讨论(0)
  • 2020-11-22 05:58

    For windows I use following:

    Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start();
    new Thread(() -> {
        Scanner sc = new Scanner(process.getInputStream());
        if (sc.hasNextLine()) sc.nextLine();
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String[] parts = line.split(",");
            String unq = parts[0].substring(1).replaceFirst(".$", "");
            String pid = parts[1].substring(1).replaceFirst(".$", "");
            System.out.println(unq + " " + pid);
        }
    }).start();
    process.waitFor();
    System.out.println("Done");
    
    0 讨论(0)
提交回复
热议问题