Skip to content

Instantly share code, notes, and snippets.

@fukata
Last active March 21, 2022 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fukata/7975794649303fc04aaee350ad33fd83 to your computer and use it in GitHub Desktop.
Save fukata/7975794649303fc04aaee350ad33fd83 to your computer and use it in GitHub Desktop.
Windowsの壁紙を変更する
/// 現在の壁紙のファイルパス
String wallpaperFilePath = path.join(
"path", "to", "wallpaper.jpg");
/// 壁紙を変更するボタンが押された時の処理。
void _handleChangeWallpaper() {
var file = File(wallpaperFilePath);
if (!file.existsSync()) {
// ファイルが存在しない
log("画像が存在しない。 filePath=$wallpaperFilePath");
return;
}
log("壁紙を変更する。 filePath=$wallpaperFilePath");
final hr = CoInitializeEx(
nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (FAILED(hr)) {
throw WindowsException(hr);
}
var desktopWallpaper = DesktopWallpaper.createInstance();
Pointer<Utf16> wallpaperFilePathPtr = wallpaperFilePath.toNativeUtf16();
try {
int result = FALSE;
// モニタの数を取得する
Pointer<Uint32> monitorDevicePathCountPtr = calloc<Uint32>();
result =
desktopWallpaper.GetMonitorDevicePathCount(monitorDevicePathCountPtr);
if (result != S_OK) {
free(monitorDevicePathCountPtr);
throw WindowsException(result);
}
log("result=$result, monitorDevicePathCountPtr.value=${monitorDevicePathCountPtr.value}");
// すべてのモニタに壁紙を設定する
for (var i = 0; i < monitorDevicePathCountPtr.value; i++) {
Pointer<Pointer<Utf16>> monitorIdPtr = calloc<Pointer<Utf16>>();
result = desktopWallpaper.GetMonitorDevicePathAt(i, monitorIdPtr);
if (result != S_OK) {
free(monitorIdPtr);
throw WindowsException(result);
}
log("result=$result, monitorIdPtr=${monitorIdPtr}");
log("change wallpaper. i=$i");
result = desktopWallpaper.SetWallpaper(monitorIdPtr.value, wallpaperFilePathPtr);
if (result != S_OK) {
free(monitorIdPtr);
throw WindowsException(result);
}
free(monitorIdPtr);
}
free(monitorDevicePathCountPtr);
} finally {
free(wallpaperFilePathPtr);
free(desktopWallpaper.ptr);
CoUninitialize();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment