[英]How to Change Desktop Images in Wpf C#
我是wpf的新手,請告訴我如何通過代碼更改桌面牆紙。
我已經讀過很少的話題,但是我似乎無法提出WPF中的解決方案。
問題是當我致電SetWallpaper時,桌面牆紙不會更改。
下面是make代碼:
public static ArrayList images;
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
public enum StyleS_Wallpaper : int
{
Tiled, Centered, Stretched
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(
int uAction, int uParam, string lpvParam, int fuWinIni);
private void OpenExecuted(object sender, ExecutedRoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Multiselect = true;
ofd.Filter = "Image Files (*.jpg)|*.jpg|Image Files (*.png)|*.png|Image File (*.gif)|*.gif|Image File (*.bmp)|*.bmp|Image Files (*.png)|*.png";
//ofd.RestoreDirectory = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
FileNames = ofd.FileNames;
if (images == null)
{
images = new ArrayList();
newlist = new List<string>();
}
for (int i = 0; i < FileNames.Length; i++)
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(FileNames[i]);
bitmap.EndInit();
images.Add(bitmap);
newlist.Add(FileNames[i]);
NextCount++;
}
}
}
public void SetWallpaper(string path,StyleS_Wallpaper selected)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (selected == StyleS_Wallpaper.Stretched)
{
key.SetValue(@"WallpaperStyle", 2.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (selected == StyleS_Wallpaper.Centered)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (selected == StyleS_Wallpaper.Tiled)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 1.ToString());
}
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
path,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
private void CenterImage_Click(object sender, RoutedEventArgs e)
{
BitmapImage img = (BitmapImage)images[currentPicture];
string Path = img.UriSource.ToString();
string name = "0";
// TrimingString Returns the string path as C:\Documents and Settings\ProZec\Desktop\WallPapers
TrimingString(Path, ref name, true);
SetWallpaper(name, StyleS_Wallpaper.Centered);
}
您是否正在使用BMP文件? 如果不是,則應先嘗試將其轉換,然后再使用SPI_SETDESKWALLPAPER。
WPF確實與此無關。 設置桌面背景僅是簡單的C#和Windows API工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.