使用 Java 在 Windows 10 中设置壁纸

Setting the wallpaper in Windows 10 using Java

我在 Whosebug 上阅读了关于同一问题的其他问题,但其中 none 对我有用。我使用的是 jna 5.8.0,但每次我尝试完成这项工作时,墙纸都设置为黑色。我没有收到任何错误消息

public class Main {
    public static void main(String []args) {
        windowsChange("INSERT IMAGE PATH HERE");
    }

    interface User32 extends Library {
        User32 INSTANCE = (User32) Native.load("user32",User32.class,W32APIOptions.DEFAULT_OPTIONS);
        boolean SystemParametersInfo (int one, int two, String s ,int three);
    }
    static void windowsChange(String path) {
        User32.INSTANCE.SystemParametersInfo(0x0014, 0, path , 1);
    }
}

我完全没有使用 jna 的经验,也没有使用过 OS。有解决办法吗?

您已从 question 复制了一个答案。如果路径是垃圾,Windows 将背景设置为黑屏,因此您应该在调用 SystemParametersInfoA.

之前使用 Files.isRegularFile(Path.of(xyz))new File(xyz).isFile() 测试您提供的路径是否存在
private static final int SPI_SETDESKWALLPAPER  = 0x0014;
private static final int SPIF_UPDATEINIFILE    = 0x01;
private static final int SPIF_SENDCHANGE       = 0x02;
User32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);