gpt4 book ai didi

c# - 如何以编程方式更改我的 Windows 桌面墙纸?

转载 作者:可可西里 更新时间:2023-11-01 08:20:05 24 4
gpt4 key购买 nike

我想使用 C# 为 Windows XP 设置壁纸。我已经开发了代码,因此它可以在 Windows 7 中完美运行,但显然它在 XP 中不一样。我将该墙纸添加为资源,将其编译操作设置为 Content 和 Always copy。奇怪的是,它在桌面的属性对话框中设置了正确的墙纸名称。但是,未设置墙纸。我的代码如下所示:

public sealed class Wallpaper
{
Wallpaper() { }

const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

public enum Style : int
{
Tiled,
Centered,
Stretched
}

public static void Set(string wpaper, Style style)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (style == Style.Stretched)
{
key.SetValue(@"WallpaperStyle", 2.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}

if (style == Style.Centered)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}

if (style == Style.Tiled)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 1.ToString());
}

string tempPath = "Resources\\"+wpaper;
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
}

调用 Wallpaper.Set("wpapername") 时,它从项目资源中获取墙纸。它适用于 Win7,但不适用于 WinXP。我做错了什么吗?

最佳答案

好吧,这有点尴尬,但我会用我发现的来回答我自己的问题。

我不得不重用已接受的答案 here 中的更多代码.基本上 XP 中的问题是它需要使用 bmp 文件,所以我设法使用前面的示例和一些调整将项目资源转换为 bmp 文件。 Set 方法以这种方式完美地工作:

public static void Set(string wpaper, Style style)
{
using(System.Drawing.Image img = System.Drawing.Image.FromFile(Path.GetFullPath(wpaper)))
{
string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");

img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);

}

RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);

if (style == Style.Stretched)
{
key.SetValue(@"WallpaperStyle", 2.ToString());

key.SetValue(@"TileWallpaper", 0.ToString());

}

if (style == Style.Centered)
{
key.SetValue(@"WallpaperStyle", 1.ToString());

key.SetValue(@"TileWallpaper", 0.ToString());

}

if (style == Style.Tiled)
{
key.SetValue(@"WallpaperStyle", 1.ToString());

key.SetValue(@"TileWallpaper", 1.ToString());

}

SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

}

重要的部分在这段代码的第三行(System.Drawing.Image.FromFile(Path.GetFullPath(wpaper));)。

关于c# - 如何以编程方式更改我的 Windows 桌面墙纸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8414635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com