Search code examples
javawindowsjnawallpaper

Change Windows 10 Wallpaper in Java


I wanted to change my Windows Wallpaper using Java and searched the web for a solution. If found this code on StackOverflow.

import java.util.HashMap;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.*;

public class WallpaperChanger {
   public static void main(String[] args) {
      //supply your own path instead of using this one
      String path = "D:\\stone.png";

      SPI.INSTANCE.SystemParametersInfo(
          new UINT_PTR(SPI.SPI_SETDESKWALLPAPER), 
          new UINT_PTR(0), 
          path, 
          new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
   }

   public interface SPI extends StdCallLibrary {

      //from MSDN article
      long SPI_SETDESKWALLPAPER = 20;
      long SPIF_UPDATEINIFILE = 0x01;
      long SPIF_SENDWININICHANGE = 0x02;

      @SuppressWarnings("serial")
      SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
         {
            put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
            put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
         }
      });

      boolean SystemParametersInfo(
          UINT_PTR uiAction,
          UINT_PTR uiParam,
          String pvParam,
          UINT_PTR fWinIni
        );
    }
}

But it doesn't work for me, I get this error:

Exception in thread "main" java.lang.NoSuchMethodError: com.sun.jna.IntegerType.(IJZ)V at com.sun.jna.platform.win32.WinDef$UINT_PTR.(WinDef.java:566) at de.dogyman.bc.main.WallpaperChanger.main(WallpaperChanger.java:15)

I have never worked with JNA before and I don't really have an idea what the code does exactly, so I don't know where the Error comes from.

I imported these jars into my Build Path:

JNA Platform

JNA

I hope someone can help me with finding a solution or give me another way of changing my wallpaper with Java.


Solution

  • You are using incompatible versions of jna.jar and jna-platform.jar. You can download a latest version of these jars at https://github.com/java-native-access/jna