import com.sun.jna.platform.win32.Kernel32; //導入方法依賴的package包/類
private static Map findProcessPIDs(Kernel32 kernel32) {
Map processes = new HashMap();
String matlabExe = "matlab.exe";
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
// gets all current running processes
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
if (kernel32.Process32First(snapshot, processEntry)) {
while (kernel32.Process32Next(snapshot, processEntry)) {
String exePath = Native.toString(processEntry.szExeFile);
exePath = exePath.toLowerCase();
// check if its a matlab process
if (!exePath.equalsIgnoreCase(matlabExe)) {
continue;
}
WinNT.HANDLE hProcess = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false,
processEntry.th32ProcessID.intValue());
// gets process path
if (hProcess != null && hProcess.getPointer() != null) {
char[] filePath = new char[1024];
Psapi32.INSTANCE.GetModuleFileNameExW(hProcess.getPointer(), null, filePath, 256);
String processPath = Native.toString(filePath);
int pid = kernel32.GetProcessId(hProcess);
processes.put(processPath, pid);
}
}
}
return processes;
}