How can we get the main title of the application from the processId of that application.
Can we use the ProcessHandler to get the window title?
In Java 9 and later, you can use the ProcessHandle
class to get information about a running process:
public class PH {
public static void main(String[] args) {
ProcessHandle.allProcesses().forEach(PH::info);
}
private static void info(final ProcessHandle processHandle) {
processHandle.info().user().ifPresent(PH::print);
processHandle.info().command().ifPresent(PH::print);
processHandle.info().commandLine().ifPresent(PH::print);
System.out.println();
}
private static void print(final String s) {
System.out.print(String.format("%s\t", s));
}
}
Approximate console output:
root /usr/libexec/secd /usr/libexec/secd
root /usr/libexec/trustd /usr/libexec/trustd --agent
user /usr/libexec/lsd /usr/libexec/lsd
I'm not sure that you will be able to get the title of an application by this way, but you can check another methods of ProcessHandle.Info class.
Also you can try to use OS-specific utils for getting information about processes:
ps -e
for Linux and Mac (you can read more about it here)tasklist.exe
for Windows (you can read more about it here)In order to call that commands you can use the next code:
String command = "ps -e";
Process process = Runtime.getRuntime().exec(command);
// Get the input stream of the command's output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Actually the similar question have been already asked, maybe you will find something useful here.
Example:
In order to get "window title" of all processes in OS Windows, you can run the next command:
tasklist /v /fo list |find /i "window title" |find /v "N/A"
It will print something like this:
...
Window Title: Untitled - Notepad
Window Title: Command Prompt
...
It means you can run that command using Runtime.getRuntime().exec(command)
as I explained above:
String command = "tasklist /v /fo list |find /i \"window title\" |find /v \"N/A\"";
Process process = Runtime.getRuntime().exec(command);
// Get the input stream of the command's output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}