How to Change Desktop Images in Wpf C#
I AM new to wpf can you please tell me how to change desktop wallpaper by code.
i have read few topics over this but i cant seem to come up with the solution in WPF.
The problem is the desktop Wallpaper Does not changes when i call SetWallpaper.
Below is make code:
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.T开发者_运维百科oString());
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);
}
Are you using a BMP file? If not, you should try converting it first before using SPI_SETDESKWALLPAPER.
WPF really has nothing to do with this. Setting the desktop background is just plain C# and Windows API work.
精彩评论