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 process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.
Finally, with Java 9+ it is possible with
ProcessHandle
:Output:
Using code to parse
ps aux
for linux andtasklist
for windows are your best options, until something more general comes along.For windows, you can reference: http://www.rgagnon.com/javadetails/java-0593.html
Linux can pipe the results of
ps aux
throughgrep
too, which would make processing/searching quick and easy. I'm sure you can find something similar for windows too.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:
then you can find if it's already running in J9, by:
The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist).
Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.
YAJSW (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven't tried calling this code directly, but YAJSW works really well when I've used it in the past, so you shouldn't have too many worries.
This is my code for a function that gets the tasks and gets their names, also adding them into a list to be accessed from a list. It creates temp files with the data, reads the files and gets the task name with the .exe suffix, and arranges the files to be deleted when the program has exited with System.exit(0), it also hides the processes being used to get the tasks and also java.exe so that the user can't accidentally kill the process that runs the program all together.