90 lines
2.0 KiB
Go
90 lines
2.0 KiB
Go
//go:build windows
|
|
|
|
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"unsafe"
|
|
|
|
"golang.org/x/sys/windows"
|
|
"golang.org/x/sys/windows/registry"
|
|
)
|
|
|
|
const (
|
|
spiSetDesktopWallpaper = 0x0014
|
|
spifUpdateINIFile = 0x0001
|
|
spifSendChange = 0x0002
|
|
)
|
|
|
|
var (
|
|
user32 = windows.NewLazySystemDLL("user32.dll")
|
|
procSystemParametersInfoW = user32.NewProc("SystemParametersInfoW")
|
|
)
|
|
|
|
func validWallpaperStyle(style string) bool {
|
|
switch style {
|
|
case "keep", "fill", "fit", "stretch", "tile", "center", "span":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func setWallpaper(path, style string) error {
|
|
absPath, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if style != "keep" {
|
|
if err := setWallpaperStyle(style); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
pathPtr, err := windows.UTF16PtrFromString(absPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r1, _, callErr := procSystemParametersInfoW.Call(
|
|
spiSetDesktopWallpaper,
|
|
0,
|
|
uintptr(unsafe.Pointer(pathPtr)),
|
|
spifUpdateINIFile|spifSendChange,
|
|
)
|
|
if r1 == 0 {
|
|
if callErr != nil && !errors.Is(callErr, windows.ERROR_SUCCESS) {
|
|
return fmt.Errorf("调用 Windows 壁纸接口: %w", callErr)
|
|
}
|
|
return errors.New("Windows 拒绝设置壁纸")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func setWallpaperStyle(style string) error {
|
|
values := map[string][2]string{
|
|
"fill": {"10", "0"},
|
|
"fit": {"6", "0"},
|
|
"stretch": {"2", "0"},
|
|
"tile": {"0", "1"},
|
|
"center": {"0", "0"},
|
|
"span": {"22", "0"},
|
|
}
|
|
value, ok := values[style]
|
|
if !ok {
|
|
return fmt.Errorf("不支持的壁纸显示方式: %s", style)
|
|
}
|
|
key, err := registry.OpenKey(registry.CURRENT_USER, `Control Panel\Desktop`, registry.SET_VALUE)
|
|
if err != nil {
|
|
return fmt.Errorf("打开壁纸设置: %w", err)
|
|
}
|
|
defer key.Close()
|
|
if err := key.SetStringValue("WallpaperStyle", value[0]); err != nil {
|
|
return fmt.Errorf("设置壁纸样式: %w", err)
|
|
}
|
|
if err := key.SetStringValue("TileWallpaper", value[1]); err != nil {
|
|
return fmt.Errorf("设置壁纸平铺方式: %w", err)
|
|
}
|
|
return nil
|
|
}
|