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

后端 未结 14 1331
抹茶落季
抹茶落季 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:31

    You can easily retrieve the list of running processes using jProcesses

    List<ProcessInfo> processesList = JProcesses.getProcessList();
    
    for (final ProcessInfo processInfo : processesList) {
        System.out.println("Process PID: " + processInfo.getPid());
        System.out.println("Process Name: " + processInfo.getName());
        System.out.println("Process Used Time: " + processInfo.getTime());
        System.out.println("Full command: " + processInfo.getCommand());
        System.out.println("------------------");
    }
    
    0 讨论(0)
  • Using code to parse ps aux for linux and tasklist 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 through grep too, which would make processing/searching quick and easy. I'm sure you can find something similar for windows too.

    0 讨论(0)
  • 2020-11-22 05:33

    There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.

    If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.

    0 讨论(0)
  • 2020-11-22 05:40

    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.

    0 讨论(0)
  • 2020-11-22 05:46

    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.

    private static final DefaultListModel tasks = new DefaultListModel();
    
    public static void getTasks()
    {
        new Thread()
        {
            @Override
            public void run()
            {
                try 
                {
                    File batchFile = File.createTempFile("batchFile", ".bat");
                    File logFile = File.createTempFile("log", ".txt");
                    String logFilePath = logFile.getAbsolutePath();
                    try (PrintWriter fileCreator = new PrintWriter(batchFile)) 
                    {
                        String[] linesToPrint = {"@echo off", "tasklist.exe >>" + logFilePath, "exit"};
                        for(String string:linesToPrint)
                        {
                            fileCreator.println(string);
                        }
                        fileCreator.close();
                    }
                    int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();
                    if(task == 0)
                    {
                        FileReader fileOpener = new FileReader(logFile);
                        try (BufferedReader reader = new BufferedReader(fileOpener))
                        {
                            String line;
                            while(true)
                            {
                                line = reader.readLine();
                                if(line != null)
                                {
                                    if(line.endsWith("K"))
                                    {
                                        if(line.contains(".exe"))
                                        {
                                            int index = line.lastIndexOf(".exe", line.length());
                                            String taskName = line.substring(0, index + 4);
                                            if(! taskName.equals("tasklist.exe") && ! taskName.equals("cmd.exe") && ! taskName.equals("java.exe"))
                                            {
                                                tasks.addElement(taskName);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    reader.close();
                                    break;
                                }
                            }
                        }
                    }
                    batchFile.deleteOnExit();
                    logFile.deleteOnExit();
                } 
                catch (FileNotFoundException ex) 
                {
                    Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
                } 
                catch (IOException | InterruptedException ex) 
                {
                    Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
                }
                catch (NullPointerException ex)
                {
                    // This stops errors from being thrown on an empty line
                }
            }
        }.start();
    }
    
    public static void killTask(String taskName)
    {
        new Thread()
        {
            @Override
            public void run()
            {
                try 
                {
                    Runtime.getRuntime().exec("taskkill.exe /IM " + taskName);
                } 
                catch (IOException ex) 
                {
                    Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }.start();
    }
    
    0 讨论(0)
  • 2020-11-22 05:48

    On Windows there is an alternative using JNA:

    import com.sun.jna.Native;
    import com.sun.jna.platform.win32.*;
    import com.sun.jna.win32.W32APIOptions;
    
    public class ProcessList {
    
        public static void main(String[] args) {
            WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);
    
            WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
    
            Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
    
            while (winNT.Process32Next(snapshot, processEntry)) {
                System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
            }
    
            winNT.CloseHandle(snapshot);
        }
    }
    
    0 讨论(0)
提交回复
热议问题