How to get processId from windowHandle in Java?

51 Views Asked by At

Is is feasible to get the process Id from windowHandle or even vice versa in Java?

We have the option to get the thread from the windowHandle in Java

User32.INSTANCE.GetWindowThreadProcessId(desktopWindow.getHWND(),null);

but how would be relate this thread to the processId

1

There are 1 best solutions below

0
Rob Spoor On

From GetWindowThreadProcessId

[out, optional] lpdwProcessId

Type: LPDWORD

A pointer to a variable that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable; otherwise, it does not.

In other words, pass an IntByReference, and afterwards retrieve its value. For instance (error checking omitted):

IntByReference lpdwProcessId = new IntByReference();
User32.INSTANCE.GetWindowThreadProcessId(desktopWindow.getHWND(), lpdwProcessId);
Optional<ProcessHandle> processHandle = ProcessHandle.of(lpdwProcessId.getValue());