com.sun.jna.platform.win32.Kernel32 Java Examples

The following examples show how to use com.sun.jna.platform.win32.Kernel32. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandLineArgumentParser.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
private static void parseAffinity(Stack<String> args) {
    if (Platform.isWindows()) {
        if (args.isEmpty()) {
            System.err.println("affinity parameter expected");
            badArguments("affinity");
        }
        try {
            int affinityMask = Integer.parseInt(args.pop());
            Kernel32.INSTANCE.SetProcessAffinityMask(Kernel32.INSTANCE.GetCurrentProcess(), affinityMask);
        } catch (NumberFormatException nex) {
            System.err.println("Bad affinityMask value");
        }
    } else {
        System.err.println("Process affinity setting is only available on Windows platform.");
    }
}
 
Example #2
Source File: SpringBootManagedContainer.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected static Integer windowsProcessId(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    /* determine the pid on windows plattforms */
    try {
      Field f = process.getClass().getDeclaredField("handle");
      f.setAccessible(true);
      long handl = f.getLong(process);

      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE handle = new WinNT.HANDLE();
      handle.setPointer(Pointer.createConstant(handl));
      int ret = kernel.GetProcessId(handle);
      log.debug("Detected pid: {}", ret);
      return ret;
    } catch (Throwable ex) {
      throw new RuntimeException("Cannot fetch windows pid!", ex);
    }
  }
  return null;
}
 
Example #3
Source File: WinProcessManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static int getProcessId(Process process) {
  String processClassName = process.getClass().getName();
  if (processClassName.equals("java.lang.Win32Process") || processClassName.equals("java.lang.ProcessImpl")) {
    try {
      if (SystemInfo.IS_AT_LEAST_JAVA9) {
        //noinspection JavaReflectionMemberAccess
        return ((Long)Process.class.getMethod("pid").invoke(process)).intValue();
      }

      long handle = assertNotNull(ReflectionUtil.getField(process.getClass(), process, long.class, "handle"));
      return Kernel32.INSTANCE.GetProcessId(new WinNT.HANDLE(Pointer.createConstant(handle)));
    }
    catch (Throwable t) {
      throw new IllegalStateException("Failed to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME, t);
    }
  }

  throw new IllegalStateException("Unable to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME);
}
 
Example #4
Source File: ProcessHelper.java    From buck with Apache License 2.0 6 votes vote down vote up
@Nullable
private Long windowsProcessId(Object process) {
  Class<?> clazz = process.getClass();
  if (clazz.getName().equals("java.lang.Win32Process")
      || clazz.getName().equals("java.lang.ProcessImpl")) {
    try {
      Field f = clazz.getDeclaredField("handle");
      f.setAccessible(true);
      long peer = f.getLong(process);
      Pointer pointer = Pointer.createConstant(peer);
      WinNT.HANDLE handle = new WinNT.HANDLE(pointer);
      return (long) Kernel32.INSTANCE.GetProcessId(handle);
    } catch (Exception e) {
      LOG.warn(e, "Cannot get process id!");
    }
  }
  return null;
}
 
Example #5
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static List<WinNT.HANDLE> mockEventHandles(WEvtApi wEvtApi, Kernel32 kernel32, List<String> eventXmls) {
    List<WinNT.HANDLE> eventHandles = new ArrayList<>();
    for (String eventXml : eventXmls) {
        WinNT.HANDLE eventHandle = mock(WinNT.HANDLE.class);
        when(wEvtApi.EvtRender(isNull(), eq(eventHandle), eq(WEvtApi.EvtRenderFlags.EVENT_XML),
                anyInt(), any(Pointer.class), any(Pointer.class), any(Pointer.class))).thenAnswer(invocation -> {
            Object[] arguments = invocation.getArguments();
            Pointer bufferUsed = (Pointer) arguments[5];
            byte[] array = StandardCharsets.UTF_16LE.encode(eventXml).array();
            if (array.length > (int) arguments[3]) {
                when(kernel32.GetLastError()).thenReturn(W32Errors.ERROR_INSUFFICIENT_BUFFER).thenReturn(W32Errors.ERROR_SUCCESS);
            } else {
                ((Pointer) arguments[4]).write(0, array, 0, array.length);
            }
            bufferUsed.setInt(0, array.length);
            return false;
        });
        eventHandles.add(eventHandle);
    }
    return eventHandles;
}
 
Example #6
Source File: OSUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @param process NiFi Process Reference
 * @param logger  Logger Reference for Debug
 * @return        Returns pid or null in-case pid could not be determined
 * This method takes {@link Process} and {@link Logger} and returns
 * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
 * In-case it fails to determine the pid, it will return Null.
 * Purpose for the Logger is to log any interaction for debugging.
 */
private static Long getWindowsProcessId(final Process process, final Logger logger) {
    /* determine the pid on windows plattforms */
    try {
        Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handl = f.getLong(process);

        Kernel32 kernel = Kernel32.INSTANCE;
        WinNT.HANDLE handle = new WinNT.HANDLE();
        handle.setPointer(Pointer.createConstant(handl));
        int ret = kernel.GetProcessId(handle);
        logger.debug("Detected pid: {}", ret);
        return Long.valueOf(ret);
    } catch (final IllegalAccessException | NoSuchFieldException nsfe) {
        logger.debug("Could not find PID for child process due to {}", nsfe);
    }
    return null;
}
 
Example #7
Source File: WinProcess.java    From sheepit-client with GNU General Public License v2.0 6 votes vote down vote up
private List<WinProcess> getChildren() throws IOException {
	ArrayList<WinProcess> result = new ArrayList<WinProcess>();
	
	WinNT.HANDLE hSnap = this.kernel32lib.CreateToolhelp32Snapshot(Kernel32Lib.TH32CS_SNAPPROCESS, new DWORD(0));
	Kernel32Lib.PROCESSENTRY32.ByReference ent = new Kernel32Lib.PROCESSENTRY32.ByReference();
	if (!this.kernel32lib.Process32First(hSnap, ent)) {
		return result;
	}
	do {
		if (ent.th32ParentProcessID.intValue() == this.pid) {
			try {
				result.add(new WinProcess(ent.th32ProcessID.intValue()));
			}
			catch (IOException e) {
				System.err.println("WinProcess::getChildren, IOException " + e);
			}
		}
	}
	while (this.kernel32lib.Process32Next(hSnap, ent));
	
	Kernel32.INSTANCE.CloseHandle(hSnap);
	
	return result;
}
 
Example #8
Source File: WinUtil.java    From SikuliX1 with MIT License 6 votes vote down vote up
public static List<ProcessInfo> allProcesses() {
  List<ProcessInfo> processList = new ArrayList<ProcessInfo>();

  HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot(
      Tlhelp32.TH32CS_SNAPPROCESS, new DWORD(0));

  try {
    Tlhelp32.PROCESSENTRY32.ByReference pe
        = new Tlhelp32.PROCESSENTRY32.ByReference();
    for (boolean more = Kernel32.INSTANCE.Process32First(snapshot, pe);
         more;
         more = Kernel32.INSTANCE.Process32Next(snapshot, pe)) {
      int pid = pe.th32ProcessID.intValue();
      String name = getProcessImageName(pe.th32ProcessID.intValue());
      if (null == name) {
        continue;
      }
      processList.add(new ProcessInfo(pid, name));
    }
    return processList;
  } finally {
    Kernel32.INSTANCE.CloseHandle(snapshot);
  }
}
 
Example #9
Source File: WindowsProcessExecutor.java    From Java-Auto-Update with Apache License 2.0 6 votes vote down vote up
@Override
public String findProcessId(Process process) throws NoSuchFieldException, IllegalAccessException {
    if (process.getClass().getName().equals("java.lang.Win32Process")
            || process.getClass().getName().equals("java.lang.ProcessImpl")) {
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handleNumber = f.getLong(process);

            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handleNumber));
            int pid = kernel.GetProcessId(handle);
            log.debug("Found pid for managed process: {}", pid);
            return pid + "";
    }
    return null;
}
 
Example #10
Source File: WinUtil.java    From SikuliX1 with MIT License 6 votes vote down vote up
private static String getProcessImageName(int pid) {
  HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(
      0x1000,
      false,
      pid);

  if (hProcess != null) {
    try {
      char[] imageNameChars = new char[1024];
      IntByReference imageNameLen
          = new IntByReference(imageNameChars.length);
      if (Kernel32.INSTANCE.QueryFullProcessImageName(hProcess, 0, imageNameChars, imageNameLen)) {
        String name = FilenameUtils.getName(new String(imageNameChars, 0, imageNameLen.getValue()));
        return name;
      }
      return null;
    } finally {
      Kernel32.INSTANCE.CloseHandle(hProcess);
    }
  }
  return null;
}
 
Example #11
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static List<WinNT.HANDLE> mockEventHandles(WEvtApi wEvtApi, Kernel32 kernel32, List<String> eventXmls) {
    List<WinNT.HANDLE> eventHandles = new ArrayList<>();
    for (String eventXml : eventXmls) {
        WinNT.HANDLE eventHandle = mock(WinNT.HANDLE.class);
        when(wEvtApi.EvtRender(isNull(WinNT.HANDLE.class), eq(eventHandle), eq(WEvtApi.EvtRenderFlags.EVENT_XML),
                anyInt(), any(Pointer.class), any(Pointer.class), any(Pointer.class))).thenAnswer(invocation -> {
            Object[] arguments = invocation.getArguments();
            Pointer bufferUsed = (Pointer) arguments[5];
            byte[] array = Charsets.UTF_16LE.encode(eventXml).array();
            if (array.length > (int) arguments[3]) {
                when(kernel32.GetLastError()).thenReturn(W32Errors.ERROR_INSUFFICIENT_BUFFER).thenReturn(W32Errors.ERROR_SUCCESS);
            } else {
                ((Pointer) arguments[4]).write(0, array, 0, array.length);
            }
            bufferUsed.setInt(0, array.length);
            return false;
        });
        eventHandles.add(eventHandle);
    }
    return eventHandles;
}
 
Example #12
Source File: OSUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * @param process NiFi Registry Process Reference
 * @param logger  Logger Reference for Debug
 * @return        Returns pid or null in-case pid could not be determined
 * This method takes {@link Process} and {@link Logger} and returns
 * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
 * In-case it fails to determine the pid, it will return Null.
 * Purpose for the Logger is to log any interaction for debugging.
 */
private static Long getWindowsProcessId(final Process process, final Logger logger) {
    /* determine the pid on windows plattforms */
    try {
        Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handl = f.getLong(process);

        Kernel32 kernel = Kernel32.INSTANCE;
        WinNT.HANDLE handle = new WinNT.HANDLE();
        handle.setPointer(Pointer.createConstant(handl));
        int ret = kernel.GetProcessId(handle);
        logger.debug("Detected pid: {}", ret);
        return Long.valueOf(ret);
    } catch (final IllegalAccessException | NoSuchFieldException nsfe) {
        logger.debug("Could not find PID for child process due to {}", nsfe);
    }
    return null;
}
 
Example #13
Source File: PipeOutputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
public PipeOutputStream(String pipeName, boolean newPipe) throws IOException {
    if (!Platform.isWindows()) {
        throw new IOException("Cannot create Pipe on nonWindows OS");
    }
    String fullPipePath = "\\\\.\\pipe\\" + pipeName;
    if (newPipe) {
        pipe = Kernel32.INSTANCE.CreateNamedPipe(fullPipePath, Kernel32.PIPE_ACCESS_OUTBOUND, Kernel32.PIPE_TYPE_BYTE, 1, 4096, 4096, 0, null);
        if (pipe == null || !Kernel32.INSTANCE.ConnectNamedPipe(pipe, null)) {
            throw new IOException("Cannot connect to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
        }
    } else {
        pipe = Kernel32.INSTANCE.CreateFile(fullPipePath, Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_WRITE, null, Kernel32.OPEN_EXISTING, Kernel32.FILE_ATTRIBUTE_NORMAL, null);
        if (pipe == null) {
            throw new IOException("Cannot connect to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
        }
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                close();
            } catch (IOException ex) {
                //ignore
            }
        }

    });
}
 
Example #14
Source File: PipeOutputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void write(int b) throws IOException {
    byte[] data = new byte[]{(byte) b};
    IntByReference ibr = new IntByReference();
    boolean result = Kernel32.INSTANCE.WriteFile(pipe, data, data.length, ibr, null);
    if (!result) {
        throw new IOException("Cannot write to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
    }
    if (ibr.getValue() != data.length) {
        throw new IOException("Cannot write to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
    }
}
 
Example #15
Source File: PipeOutputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void close() throws IOException {
    if (!closed) {
        Kernel32.INSTANCE.CloseHandle(pipe);
        closed = true;
    }
}
 
Example #16
Source File: PipeInputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
public PipeInputStream(String pipeName, boolean newpipe) throws IOException {
    if (!Platform.isWindows()) {
        throw new IOException("Cannot create Pipe on nonWindows OS");
    }
    String fullPipePath = "\\\\.\\pipe\\" + pipeName;
    if (newpipe) {
        pipe = Kernel32.INSTANCE.CreateNamedPipe(fullPipePath, Kernel32.PIPE_ACCESS_INBOUND, Kernel32.PIPE_TYPE_BYTE, 1, 4096, 4096, 0, null);
        if (pipe == null || !Kernel32.INSTANCE.ConnectNamedPipe(pipe, null)) {
            throw new IOException("Cannot connect to the pipe");
        }
    } else {
        pipe = Kernel32.INSTANCE.CreateFile(fullPipePath, Kernel32.GENERIC_READ, Kernel32.FILE_SHARE_READ, null, Kernel32.OPEN_EXISTING, Kernel32.FILE_ATTRIBUTE_NORMAL, null);
    }
    if (pipe == null) {
        throw new IOException("Cannot connect to the pipe");
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                close();
            } catch (IOException ex) {
                //ignore
            }
        }

    });
}
 
Example #17
Source File: PipeInputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void close() throws IOException {
    if (!closed) {
        Kernel32.INSTANCE.CloseHandle(pipe);
        closed = true;
    }
}
 
Example #18
Source File: PipeInputStream.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
private int readPipe(byte res[]) throws IOException {
    final IntByReference ibr = new IntByReference();
    int read = 0;
    while (read < res.length) {
        byte[] data = new byte[res.length - read];
        boolean result = Kernel32.INSTANCE.ReadFile(pipe, data, data.length, ibr, null);
        if (!result) {
            throw new IOException("Cannot read pipe. Error " + Kernel32.INSTANCE.GetLastError());
        }
        int readNow = ibr.getValue();
        System.arraycopy(data, 0, res, read, readNow);
        read += readNow;
    }
    return read;
}
 
Example #19
Source File: WinProcess.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
private static WinNT.HANDLE getHandleByPid(int pid_) throws IOException {
	WinNT.HANDLE handle = Kernel32.INSTANCE.OpenProcess(0x0400 | // PROCESS_QUERY_INFORMATION
					0x0800 | // PROCESS_SUSPEND_RESUME
					0x0001 | // PROCESS_TERMINATE
					0x0200 | // PROCESS_SET_INFORMATION
					0x00100000, // SYNCHRONIZE
			false, pid_);
	if (handle == null) {
		throw new IOException(
				"OpenProcess failed: " + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()) + " (pid: " + pid_ + ")");
	}
	return handle;
}
 
Example #20
Source File: EventSubscribeXmlRenderingCallback.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public EventSubscribeXmlRenderingCallback(ComponentLog logger, Consumer<String> consumer, int maxBufferSize, WEvtApi wEvtApi, Kernel32 kernel32, ErrorLookup errorLookup) {
    this.logger = logger;
    this.consumer = consumer;
    this.maxBufferSize = maxBufferSize;
    this.wEvtApi = wEvtApi;
    this.kernel32 = kernel32;
    this.size = Math.min(maxBufferSize, INITIAL_BUFFER_SIZE);
    this.errorLookup = errorLookup;
    this.buffer = new Memory(size);
    this.used = new Memory(4);
    this.propertyCount = new Memory(4);
}
 
Example #21
Source File: Windows.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
@Override public long getMemory() {
	try {
		MEMORYSTATUSEX _memory = new MEMORYSTATUSEX();
		if (Kernel32.INSTANCE.GlobalMemoryStatusEx(_memory)) {
			return _memory.ullTotalPhys.longValue() / 1024; // size in KB
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	return 0;
}
 
Example #22
Source File: Windows.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
@Override public long getFreeMemory() {
	try {
		MEMORYSTATUSEX _memory = new MEMORYSTATUSEX();
		if (Kernel32.INSTANCE.GlobalMemoryStatusEx(_memory)) {
			return _memory.ullAvailPhys.longValue() / 1024; // size in KB
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	
	return -1;
}
 
Example #23
Source File: JKernel32.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static boolean openDevice() throws IOException {
       /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */
       int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE;
       int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ;
	HandleToDevice = Kernel32.INSTANCE.CreateFile(
               Devices.getConnectedDeviceWin32().getDevPath(), 
               Access, 
               shareMode, 
               null, 
               WinNT.OPEN_EXISTING, 
               0,//WinNT.FILE_FLAG_OVERLAPPED, 
               (WinNT.HANDLE)null);
	if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError());
	return true;
}
 
Example #24
Source File: JKernel32.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static boolean openDeviceAsync() throws IOException {
       /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */
       int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE;
       int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ;
	HandleToDevice = Kernel32.INSTANCE.CreateFile(
               Devices.getConnectedDeviceWin32().getDevPath(), 
               Access, 
               shareMode, 
               null, 
               WinNT.OPEN_EXISTING, 
               WinNT.FILE_FLAG_OVERLAPPED, 
               (WinNT.HANDLE)null);
	if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError());
	return true;
}
 
Example #25
Source File: ConsumeWindowsEventLog.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that allows injection of JNA interfaces
 *
 * @param wEvtApi  event api interface
 * @param kernel32 kernel interface
 */
public ConsumeWindowsEventLog(WEvtApi wEvtApi, Kernel32 kernel32) {
    this.wEvtApi = wEvtApi == null ? loadWEvtApi() : wEvtApi;
    this.kernel32 = kernel32 == null ? loadKernel32() : kernel32;
    this.errorLookup = new ErrorLookup(this.kernel32);
    if (this.kernel32 != null) {
        name = Kernel32Util.getComputerName();
    } else {
        // Won't be able to use the processor anyway because native libraries didn't load
        name = null;
    }
}
 
Example #26
Source File: ConsumeWindowsEventLog.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Kernel32 loadKernel32() {
    try {
        return Kernel32.INSTANCE;
    } catch (Throwable e) {
        kernel32Error = e;
        return null;
    }
}
 
Example #27
Source File: EventSubscribeXmlRenderingCallback.java    From nifi with Apache License 2.0 5 votes vote down vote up
public EventSubscribeXmlRenderingCallback(ComponentLog logger, Consumer<String> consumer, int maxBufferSize, WEvtApi wEvtApi, Kernel32 kernel32, ErrorLookup errorLookup) {
    this.logger = logger;
    this.consumer = consumer;
    this.maxBufferSize = maxBufferSize;
    this.wEvtApi = wEvtApi;
    this.kernel32 = kernel32;
    this.size = Math.min(maxBufferSize, INITIAL_BUFFER_SIZE);
    this.errorLookup = errorLookup;
    this.buffer = new Memory(size);
    this.used = new Memory(4);
    this.propertyCount = new Memory(4);
}
 
Example #28
Source File: ConsumeWindowsEventLog.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private Kernel32 loadKernel32() {
    try {
        return Kernel32.INSTANCE;
    } catch (Throwable e) {
        kernel32Error = e;
        return null;
    }
}
 
Example #29
Source File: ConsumeWindowsEventLog.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that allows injection of JNA interfaces
 *
 * @param wEvtApi  event api interface
 * @param kernel32 kernel interface
 */
public ConsumeWindowsEventLog(WEvtApi wEvtApi, Kernel32 kernel32) {
    this.wEvtApi = wEvtApi == null ? loadWEvtApi() : wEvtApi;
    this.kernel32 = kernel32 == null ? loadKernel32() : kernel32;
    this.errorLookup = new ErrorLookup(this.kernel32);
    if (this.kernel32 != null) {
        name = Kernel32Util.getComputerName();
    } else {
        // Won't be able to use the processor anyway because native libraries didn't load
        name = null;
    }
}
 
Example #30
Source File: WinUtil.java    From SikuliX1 with MIT License 5 votes vote down vote up
public static List<WindowInfo> allWindows() {
  /* Initialize the empty window list. */
  final List<WindowInfo> windows = new ArrayList<>();

  /* Enumerate all of the windows and add all of the one for the
   * given process id to our list. */
  boolean result = user32.EnumWindows(
      new WinUser.WNDENUMPROC() {
        public boolean callback(
            final HWND hwnd, final Pointer data) {

          if (user32.IsWindowVisible(hwnd)) {
            IntByReference windowPid = new IntByReference();
            user32.GetWindowThreadProcessId(hwnd, windowPid);

            String windowTitle = getWindowTitle(hwnd);

            windows.add(new WindowInfo(hwnd, windowPid.getValue(), windowTitle));
          }

          return true;
        }
      },
      null);

  /* Handle errors. */
  if (!result && Kernel32.INSTANCE.GetLastError() != 0) {
    throw new RuntimeException("Couldn't enumerate windows.");
  }

  /* Return the window list. */
  return windows;
}