0
点赞
收藏
分享

微信扫一扫

自动更换壁纸

import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO;

public class AutoWallpaper {

public static void main(String[] args) throws IOException {
    //设置壁纸路径
    String wallpaperPath = "D:/Wallpapers/";
    //获取壁纸列表
    List<File> wallpapers = getWallpapers(wallpaperPath);
    //获取当前壁纸
    String currentWallpaper = getCurrentWallpaper();
    //获取当前壁纸在列表中的位置
    int currentIndex = wallpapers.indexOf(new File(currentWallpaper));
    //获取下一个壁纸的位置
    int nextIndex = (currentIndex + 1) % wallpapers.size();
    //设置下一个壁纸为桌面背景
    setWallpaper(wallpapers.get(nextIndex));
}

//获取壁纸列表
private static List<File> getWallpapers(String path) {
    List<File> wallpapers = new ArrayList<>();
    File folder = new File(path);
    File[] files = folder.listFiles();
    for (File file : files) {
        if (file.isFile() && isImageFile(file)) {
            wallpapers.add(file);
        }
    }
    return wallpapers;
}

//判断是否为图片文件
private static boolean isImageFile(File file) {
    try {
        ImageIO.read(file);
        return true;
    } catch (IOException e) {
        return false;
    }
}

//获取当前壁纸
private static String getCurrentWallpaper() throws IOException {
    String os = System.getProperty("os.name").toLowerCase();
    if (os.contains("win")) {
        //Windows系统
        Process process = Runtime.getRuntime().exec("reg query \"HKEY_CURRENT_USER\\Control Panel\\Desktop\" /v Wallpaper");
        String result = IOUtils.toString(process.getInputStream());
        String[] lines = result.split("\n");
        for (String line : lines) {
            if (line.contains("Wallpaper")) {
                return line.split("\\s+")[2];
            }
        }
    } else {
        //其他系统
        throw new UnsupportedOperationException("Unsupported operating system.");
    }
    return null;
}

//设置壁纸
private static void setWallpaper(File wallpaper) throws IOException {
    String os = System.getProperty("os.name").toLowerCase();
    if (os.contains("win")) {
        //Windows系统
        String command = "REG ADD \"HKCU\\Control Panel\\Desktop\" /v Wallpaper /t REG_SZ /d \"" + wallpaper.getAbsolutePath() + "\" /f\n" +
                "RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters";
        Runtime.getRuntime().exec(command);
    } else {
        //其他系统
        throw new UnsupportedOperationException("Unsupported operating system.");
    }
}

}

举报

相关推荐

0 条评论