【问题标题】:List all processes?列出所有进程?
【发布时间】:2017-10-24 18:13:38
【问题描述】:

如何使用 JNA 4.5.0 获取 Java 中所有正在运行的进程的列表?

我已经尝试过这段代码:

WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);
winNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
Thelp32.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);

但它不起作用,因为它是为旧版本的 JNA lib 编写的。

【问题讨论】:

    标签: java windows process jna


    【解决方案1】:

    您现在正在寻找的一些功能存在于Kernel32 类中。通过一些小的更正,您的 sn-p 工作正常:

    import com.sun.jna.Native;
    import com.sun.jna.platform.win32.Kernel32;
    import com.sun.jna.platform.win32.Tlhelp32;
    import com.sun.jna.platform.win32.WinDef;
    import com.sun.jna.platform.win32.WinNT;
    
    public class Main {
        public static void main(String[] args) {
            Kernel32 kernel = Kernel32.INSTANCE;
    
            WinNT.HANDLE snapshot = kernel.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
            Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
    
            while (kernel.Process32Next(snapshot, processEntry)) {
                System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
            }
            kernel.CloseHandle(snapshot);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多