简体   繁体   中英

Can I get handle of the process by executable name?

I am using JNA to use user32.dll and kernel32.dll. I have the sample code which can give me the handle if i specify the title of the process.

hWnd = User32.FindWindowA(null, "Call of Duty®: Modern Warfare® 3 Multiplayer");  

I really don't want to search for the process handle by the Title . Is there any method which takes the exe name? Like this:

hWnd = User32.FindWindowByExecutable ( "iw5mp.exe" );

So that, it will return 0 if this process is not running otherwise the handle.

Also, the thing is when using JNA, eclipse obviously can't auto suggest the methods present in User32 or Kernel32 dll. So, what do you do in such cases. Just google the probable method?

With Java 9, thanks to JEP 102 , it will be possible to obtain a handle of the process given an executable name, with the new ProcessHandle interface:

Optional<ProcessHandle> findByExactCommand(String command) {
    return ProcessHandle.allProcesses().filter(process -> {
        Optional<String> cmd = process.info().command();
        return cmd.isPresent() && cmd.get().equals(command);
    }).findFirst();
}

Literally answering question in title, ignoring JNA aspects, but reading comments it seems that was OP was after:

I don't think there is anything like Process.GetProcesses in java

Well, now there is;)

String passed to FindWindow() as a second parameter is NOT title of the process. It is title of some window instead. And value returned by FindWindow() is (surprise,) handle of the window. not process handle.

If title of window you want to find may change i suggest you search window by their class name (first argument of FindWindow) leaving second argument null.

Class of windows application window may be determined by Microsoft Spy++ or similar software.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM