java - 如何使用 JNA 获取 Activity 窗口的应用程序名称?

标签 java winapi jna

我有以下使用 JNA 库的代码,它输出 Activity 窗口的标题。

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”?

提前致谢

最佳答案

我发现 GetWindowModuleFilename 在大多数情况下都不起作用。然而,QueryFullProcessImageName 工作得很好。请注意,您仍然需要 OpenProcess 进程来访问图像文件名。

在控制台应用程序中尝试此操作。当您更改窗口时,它将打印出 Activity 窗口的图像文件名。

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

关于java - 如何使用 JNA 获取 Activity 窗口的应用程序名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50694754/

相关文章:

java - JNA 使用 32 位 JVM 运行时内存访问无效

c++ - 我想在EN_KILLFOCUS之后找出焦点属于哪里?

javascript - 如何使用 angularJS 删除列表对象

java - 如何将实体组件系统用于整个系统的libgdx中的舞台,组和 Actor 的游戏设计?

java - 使用 ReplaceAll() 进行询问

winapi - WinInet - 无法从 header 中删除内容长度以手动对上传进行分块

winapi - win32api 使用 SHFileStruct 从回收站还原文件

java - JNA undefined symbol

java - Compact Language Detector 2 的检测方法线程安全吗?

java - 启用 Maven 与 eclipse 集成的步骤