Skip to content

Instantly share code, notes, and snippets.

@serkanberksoy
Created August 14, 2014 12:08
Show Gist options
  • Save serkanberksoy/20c777b87b75ecfa8957 to your computer and use it in GitHub Desktop.
Save serkanberksoy/20c777b87b75ecfa8957 to your computer and use it in GitHub Desktop.
save windows form control to desktop wallpaper
/*
example windows form code to save panel as bitmap
and set that bitmap to wallpaper
*/
private void DrawControlToImage(Control ctrl, Image img)
{
Rectangle sourceRect = ctrl.ClientRectangle;
Size targetSize = new Size(img.Width, img.Height);
using (Bitmap tmp = new Bitmap(sourceRect.Width, sourceRect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
ctrl.DrawToBitmap(tmp, sourceRect);
using (Graphics g = Graphics.FromImage(img))
{
g.DrawImage(tmp, new Rectangle(Point.Empty, targetSize));
}
}
}
private void btnDraw_Click_1(object sender, EventArgs e)
{
Image img = new Bitmap(1024, 768);
DrawControlToImage(pnlMain, img);
img.Save(@"C:\test3_copy.jpg", ImageFormat.Jpeg);
Wallpaper.Set(@"C:\test3_copy.jpg", Wallpaper.Style.Stretched);
// Application.Exit();
}
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace DrawToForm
{
public static class 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)
{
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment