使用 Java 打开文件的属性窗口

问题描述 投票:0回答:2

这只是关于 Windows 中的 Java 的问题。

我需要一个调用此窗口的方法:

所以本质上该方法应该是这样的:

public void openProperties(File file){ // or String fileName

}

所以语句:

opernProperties(new File(test.txt));
应该打开上面的窗口。

所以澄清一下,我不想阅读和管理属性。我只想打开属性窗口。

java windows file properties
2个回答
2
投票

我能够使用以下命令显示文件属性窗口:

这应该会延迟 3 秒显示属性窗口。请注意,alk 讨论了如果您不希望窗口在 3 秒后自动关闭,则通过 hwnd 成员传递窗口

public static void main(String[] args) throws InterruptedException {
        ShellAPI.SHELLEXECUTEINFO shellExecuteInfo = new ShellAPI.SHELLEXECUTEINFO();
        shellExecuteInfo.lpFile = "C:\\setup.log";
        shellExecuteInfo.nShow = User32.SW_SHOW;
        shellExecuteInfo.fMask = 0x0000000C;
        shellExecuteInfo.lpVerb = "properties";
        if (Shell32.INSTANCE.ShellExecuteEx(shellExecuteInfo)){
            Thread.sleep(3000);
        }
    }

0
投票

Windows API 调用 SHObjectProperties 还将启动 Windows 文件属性对话框。您可以从 JNA、JNI 调用或尝试在 JDK16 或更高版本中作为孵化器使用 JDK 巴拿马 / 外部内存 API。

外部内存 API 是 JDK22 的一部分,因此以下代码将在 JDK22 的 Windows 中启动“属性”对话框:

public static void main(String ... args) throws Throwable {

    try(Arena arena = Arena.ofConfined())  {

        // NOTE: must use absolute path
        Path path= Path.of(args[0]).toAbsolutePath();

        // Java String to Windows Wide String:
        MemorySegment pszObjectName = arena.allocateFrom(path.toString(), StandardCharsets.UTF_16LE);

        // Invoke Windows API
        int hres = Native_h.SHObjectProperties(MemorySegment.NULL, Native_h.SHOP_FILEPATH(), pszObjectName, MemorySegment.NULL);
        System.out.println("SHObjectProperties path="+path +" hres="+hres);
    }

    // Properties dialogs will close when the this app exits
    System.out.println("Press any key to exit");
    System.in.read();
}

可以使用

jextract
命令生成本机调用绑定的源代码:

echo #include ^<shlobj_core.h^> > Native.h
jextract -lshell32 -t some.name --output generated --include-function SHObjectProperties --include-constant SHOP_FILEPATH Native.h

上面的命令将生成访问本机方法所需的 Java 调用,或者这是在 Java 中手工制作的等效定义:

class Native_h {
    private static final SymbolLookup SHELL32 = SymbolLookup.libraryLookup("shell32", Arena.global());

    // https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shobjectproperties
    private static final MethodHandle SHObjectProperties = Linker.nativeLinker().downcallHandle(
        SHELL32.find("SHObjectProperties").get(),
        FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS)
    );

    // invoke "SHObjectProperties"
    static int SHObjectProperties(MemorySegment hWnd, int shopObjectType, MemorySegment pszObjectName, MemorySegment pszPropertyPage) throws Throwable {
        return (int)SHObjectProperties.invokeExact(hWnd, shopObjectType, pszObjectName, pszPropertyPage);
    }
    // Constant needed for Properties
    static final int SHOP_FILEPATH() {
        return (int)2L;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.