Как получить имя приложения активного окна с помощью JNA? - PullRequest
0 голосов
/ 05 июня 2018

У меня есть следующий код, использующий библиотеку JNA, которая выводит заголовок активного окна.

private static final int MAX_TITLE_LENGTH = 1024;

public static void main(String[] args) throws Exception {

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    LocalDateTime now = LocalDateTime.now();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            char[] buffer = new char[MAX_TITLE_LENGTH * 2];
            HWND hwnd = User32.INSTANCE.GetForegroundWindow();
            User32.INSTANCE.GetWindowText(hwnd, buffer, MAX_TITLE_LENGTH);
            System.out.println("Active window title: " + Native.toString(buffer));
            try {
                BufferedWriter bw = new BufferedWriter(
                    new FileWriter(
                        new File("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\system\\useracivity.txt"),
                        true
                    )
                );
                bw.write(Native.toString(buffer) + " TIME WAS " + dtf.format(now));
                bw.newLine();
                bw.close();
            } catch (Exception e) {
            }
        }
    };

    Timer timer = new Timer();
    timer.schedule(task, new Date(), 5000);

}

Но как мне получить имя приложения, например для Chrome "chrome.exe"?

Заранее спасибо

1 Ответ

0 голосов
/ 16 июня 2018

Я обнаружил, что GetWindowModuleFilename на самом деле не работает большую часть времени.QueryFullProcessImageName, однако, работает просто отлично.Обратите внимание, что вам все еще нужно OpenProcess процесс для доступа к имени файла изображения.

Попробуйте это в консольном приложении.Когда вы измените окно, оно напечатает имя файла активного окна.

import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.ptr.IntByReference;

public class Main {
    public static void main(String[] args) throws Exception {
        HWND prevFg = null;

        while (true) {
            Thread.sleep(200);

            HWND fg = User32.INSTANCE.GetForegroundWindow();

            // don't print the name if it's still the same window as previously
            if (fg.equals(prevFg)) {
                continue;
            }

            String fgImageName = getImageName(fg);
            if (fgImageName == null) {
                System.out.println("Failed to get the image name!");
            } else {
                System.out.println(fgImageName);
            }

            prevFg = fg;
        }
    }

    private static String getImageName(HWND window) {
        // Get the process ID of the window
        IntByReference procId = new IntByReference();
        User32.INSTANCE.GetWindowThreadProcessId(window, procId);

        // Open the process to get permissions to the image name
        HANDLE procHandle = Kernel32.INSTANCE.OpenProcess(
                Kernel32.PROCESS_QUERY_LIMITED_INFORMATION,
                false,
                procId.getValue()
        );

        // Get the image name
        char[] buffer = new char[4096];
        IntByReference bufferSize = new IntByReference(buffer.length);
        boolean success = Kernel32.INSTANCE.QueryFullProcessImageName(procHandle, 0, buffer, bufferSize);

        // Clean up: close the opened process
        Kernel32.INSTANCE.CloseHandle(procHandle);

        return success ? new String(buffer, 0, bufferSize.getValue()) : null;
    }
}

При щелчке по моим окнам программа выводит строки, подобные этим:

C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.5\bin\idea64.exe
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.5\bin\idea64.exe
...