如何使用 Java 获取当前打开的窗口/进程列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:42:38  来源:igfitidea点击:

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

javaprocess

提问by ramayac

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

有谁知道如何使用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.

我想要做的是:列出当前打开的任务、窗口或进程打开,就像在 Windows 任务管理器中一样,但使用多平台方法 - 如果可能,只使用 Java。

采纳答案by ramayac

This is another approach to parse the the process list from the command "ps -e":

这是从命令“ ps -e”解析进程列表的另一种方法:

try {
    String line;
    Process p = Runtime.getRuntime().exec("ps -e");
    BufferedReader input =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        System.out.println(line); //<-- Parse data here.
    }
    input.close();
} catch (Exception err) {
    err.printStackTrace();
}

If you are using Windows, then you should change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this:

如果您使用的是 Windows,那么您应该更改以下行:“Process p = Runtime.getRun...”等...(第 3 行),如下所示:

Process p = Runtime.getRuntime().exec
    (System.getenv("windir") +"\system32\"+"tasklist.exe");

Hope the info helps!

希望信息有帮助!

回答by jodonnell

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).

我能想到的唯一方法是调用为您完成工作的命令行应用程序,然后对输出进行屏幕抓取(如 Linux 的 ps 和 Window 的任务列表)。

Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.

不幸的是,这意味着您必须编写一些解析例程来从两者读取数据。

Process proc = Runtime.getRuntime().exec ("tasklist.exe");
InputStream procOutput = proc.getInputStream ();
if (0 == proc.waitFor ()) {
    // TODO scan the procOutput for your data
}

回答by hazzen

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.

没有平台中立的方式来做到这一点。在 Java 1.6 版本中,添加了“桌面”类,允许以可移植的方式浏览、编辑、邮寄、打开和打印 URI。有可能有一天这个类可能会扩展到支持流程,但我对此表示怀疑。

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

如果你只是对 Java 进程感兴趣,你可以使用java.lang.managementapi 来获取 JVM 上的线程/内存信息。

回答by SamWest

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.

YAJSW(Yet Another Java Service Wrapper)看起来像是它的 org.rzo.yajsw.os.TaskList 接口的基于 JNA 的实现,用于 win32、linux、bsd 和 solaris,并且在 LGPL 许可下。这段代码我没试过直接调用,不过我以前用过YAJSW效果确实不错,大家不用太担心。

回答by Emmanuel Bourg

On Windows there is an alternative using JNA:

在 Windows 上有一个使用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);
    }
}

回答by James Oravec

Using code to parse ps auxfor linux and tasklistfor windows are your best options, until something more general comes along.

使用代码来解析ps auxlinux 和tasklistwindows 是你最好的选择,直到出现更通用的东西。

For windows, you can reference: http://www.rgagnon.com/javadetails/java-0593.html

对于windows,可以参考:http: //www.rgagnon.com/javadetails/java-0593.html

Linux can pipe the results of ps auxthrough greptoo, which would make processing/searching quick and easy. I'm sure you can find something similar for windows too.

Linux 也可以ps aux通过管道传输结果grep,这将使处理/搜索变得快速而简单。我相信你也可以为 Windows 找到类似的东西。

回答by Panchotiya Vipul

package com.vipul;

import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class BatchExecuteService extends Applet {
    public Choice choice;

    public void init() 
    {
        setFont(new Font("Helvetica", Font.BOLD, 36));
        choice = new Choice();
    }

    public static void main(String[] args) {
        BatchExecuteService batchExecuteService = new BatchExecuteService();
        batchExecuteService.run();
    }

    List<String> processList = new ArrayList<String>();

    public void run() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("D:\server.bat");
            process.getOutputStream().close();
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedrReader = new BufferedReader(
                    inputstreamreader);
            BufferedReader bufferedrReader1 = new BufferedReader(
                    inputstreamreader);

            String strLine = "";
            String x[]=new String[100];
            int i=0;
            int t=0;
            while ((strLine = bufferedrReader.readLine()) != null) 
            {
        //      System.out.println(strLine);
                String[] a=strLine.split(",");
                x[i++]=a[0];
            }
    //      System.out.println("Length : "+i);

            for(int j=2;j<i;j++)
            {
                System.out.println(x[j]);
            }
        }
        catch (IOException ioException) 
        {
            ioException.printStackTrace();
        }

    }
}
   You can create batch file like 

TASKLIST /v /FI "STATUS eq running" /FO "CSV" /FI "Username eq LHPL002\soft" /FI "MEMUSAGE gt 10000" /FI "Windowtitle ne N/A" /NH

   You can create batch file like 

TASKLIST /v /FI "STATUS eq running" /FO "CSV" /FI "Username eq LHPL002\soft" /FI "MEMUSAGE gt 10000" /FI "Windowtitle ne N/A" /NH

回答by profesor_falken

You can easily retrieve the list of running processes using jProcesses

您可以使用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("------------------");
}

回答by Stepan Yakovenko

For windows I use following:

对于 Windows,我使用以下内容:

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");

回答by Hugues M.

Finally, with Java 9+ it is possible with ProcessHandle:

最后,使用 Java 9+ 可以使用ProcessHandle

public static void main(String[] args) {
    ProcessHandle.allProcesses()
            .forEach(process -> System.out.println(processDetails(process)));
}

private static String processDetails(ProcessHandle process) {
    return String.format("%8d %8s %10s %26s %-40s",
            process.pid(),
            text(process.parent().map(ProcessHandle::pid)),
            text(process.info().user()),
            text(process.info().startInstant()),
            text(process.info().commandLine()));
}

private static String text(Optional<?> optional) {
    return optional.map(Object::toString).orElse("-");
}

Output:

输出:

    1        -       root   2017-11-19T18:01:13.100Z /sbin/init
  ...
  639     1325   www-data   2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
  ...
23082    11054    huguesm   2018-12-04T10:24:22.100Z /.../java ProcessListDemo