我想创建一个程序,将位图图像文件(
.bmp
)保存在驱动程序上并将图像设置为壁纸。我设法编写的代码将图像保存在正确的位置,但图像没有显示为壁纸。
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32
uiParam,String pvParam, UInt32 fWinIni);
private static UInt32 SPI_SETDESKWALLPAPER = 20;
private static UInt32 SPIF_UPDATEINIFILE = 0x1;
private String imageFileName = "D:\\wall.bmp";
static void Main(string[] args)
{
Bitmap bmp = new Bitmap(Properties.Resources.wall);
bmp.Save("D:\\wall.bmp");
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, "D:\\wall.bmp", SPIF_UPDATEINIFILE);
}
}
你可以尝试写在这里的这个课程:
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(Uri uri, Style style)
{
System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToString());
System.Drawing.Image img = System.Drawing.Image.FromStream(s);
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);
}
}
祝你好运!
当您致电
SPIF_SENDCHANGE
时,您还需要包含 SystemParametersInfo
。这是需要通知系统背景已更改并将导致系统响应您的更改。
SystemParametersInfo(
SPI_SETDESKWALLPAPER,
0,
@"D:\wall.bmp",
SPIF_UPDATEINIFILE | SPIF_SENDCHANGE
);
您需要为
SPIF_SENDCHANGE
添加声明,其值为 0x2
。
文档这样描述了
SPIF_SENDCHANGE
:
更新用户配置文件后广播 WM_SETTINGCHANGE 消息。
也就是说,即使没有
SPIF_SENDCHANGE
,某些系统上的桌面背景也会发生变化。所以我的猜测是你的主要问题实际上是你的位图文件。以下是您的位图文件可能存在的一些问题:
通过在 Paint 中创建一个简单的位图并更改上面的代码以使用该文件的硬编码路径,向自己证明上面的代码是有效的。这会让您相信桌面背景是可以更改的。