How to get opened application in windows(taskmanager ->application tab content) using java code

前端 未结 2 756
面向向阳花
面向向阳花 2021-01-28 05:36

Below one is used for get list of processes from the windows

       Process proc = Runtime.getRuntime().exec (\"tasklist.exe\");

2条回答
  •  遇见更好的自我
    2021-01-28 05:49

    I am trying to give the answer, even if the post is already more than one year old.

    Try with the following code snippet:

    private static final String STR_MATCH = "My Java Application";
    String strProcess;
    BufferedReader input = null;
    
    try { 
        if(System.getProperty("os.name").startsWith("Windows")) {
            Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe /v /FI \"STATUS eq RUNNING\" /FI \"imagename eq javaw.exe\"");
            input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
            while((strProcess = input.readLine()) != null) {
                if(strProcess.contains(STR_MATCH))
                    /* lot of code here */
            }
    
            // Close resources
            input.close();
    }
    catch(IOEXception ioe) {
        /* handle exception */
    }
    

    The thing to notice here is the way used to get the Process p, i.e.:

    Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe /v /FI \"STATUS eq RUNNING\" /FI \"imagename eq javaw.exe\"");
    

    The filter /FI "STATUS eq RUNNING" /FI "imagename eq javaw.exe" that has been added when invoking tasklist.exe allows to get more information related to the process javaw.exe, including the Window/Application name.

提交回复
热议问题