Get list of processes on Windows in a charset-safe way

后端 未结 4 1887
别那么骄傲
别那么骄傲 2020-12-01 19:27

This post gives a solution to retrieve the list of running processes under Windows. In essence it does:

String cmd = System.getenv(\"windir\") + \"\\\\system         


        
4条回答
  •  无人及你
    2020-12-01 19:56

    Why not use the Windows API via JNA, instead of spawning processes? Like this:

    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;
    import com.sun.jna.win32.W32APIOptions;
    import com.sun.jna.Native; 
    
    public class ListProcesses {
        public static void main(String[] args) {
            Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
            Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();          
    
            WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
            try  {
                while (kernel32.Process32Next(snapshot, processEntry)) {             
                    System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
                }
            }
            finally {
                kernel32.CloseHandle(snapshot);
            }
        } 
    }
    

    I posted a similar answer elsewhere.

提交回复
热议问题