'Non-UI application (console / server application)
#Region Project Attributes
#CommandLineArgs:
#MergeLibraries: True
#End Region
#AdditionalJar: jna-4.5.1
#AdditionalJar: jna-platform-4.5.1
Sub Process_Globals
End Sub
Sub AppStart (Args() As String)
Dim processList As List = ListWinProcesses
For Each item As String In processList
Log(item)
Next
Dim processPIDs As List = ListWinProcessPIDs("firefox.exe")
For Each item2 As Int In processPIDs
Log(item2)
Next
End Sub
'Produce a list Windows PID's and the associated EXE file
Sub ListWinProcesses() As List
Dim joMe As JavaObject = Me
Return joMe.RunMethod("listWinProcesses", Null)
End Sub
'For a given Windows EXE file, produce a list of PID's. EXE filename will be
' treated as case insensitive.
Sub ListWinProcessPIDs(process As String) As List
Dim joMe As JavaObject = Me
Return joMe.RunMethod("listWinProcessPIDs", Array As Object(process))
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
#if Java
//Adapted from: https://stackoverflow.com/a/13478508
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;
import java.util.ArrayList;
import java.util.List;
static public List listWinProcesses() {
List<String>listOfProcesses = new ArrayList<String>();
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)) {
listOfProcesses.add(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return listOfProcesses;
}
// Note: parameter process will be treated as case insensitive
static public List listWinProcessPIDs(String process) {
List<Integer>listOfPIDs = new ArrayList<Integer>();
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)) {
if(Native.toString(processEntry.szExeFile).equalsIgnoreCase(process)) {
listOfPIDs.add(Integer.parseInt(processEntry.th32ProcessID + ""));
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return listOfPIDs;
}
#End If