I'm working on a program where you can change the wallpaper of the main form "Form1" from the "Options" form. On the Options form, there is an openfiledialog where u can select an image and it copies the image to the application directory.
private void wallpaperBrowser_Click(object sender, EventArgs e)
{
wallpaperOptioncolor.Visible = false;
OpenFileDialog of = new OpenFileDialog();
of.Title = "Select Image";
of.Filter = "Image Files (*.jpg;*.jpeg,*.png,*.gif)|*.JPG;*.JPEG;*.PNG;*.GIF";
if (of.ShowDialog() == DialogResult.OK)
{
File.Copy(of.FileName, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\DesktopReborn\\CurrentWallpaper.png", true);
(this.Owner as Form1).mainBackground.Image = new Bitmap(of.FileName);
(this.Owner as Form1).BackgroundImage = new Bitmap(of.FileName);
currentWallpaper.BackgroundImage = (this.Owner as Form1).mainBackground.Image;
(this.Owner as Form1).BackgroundImageLayout = ImageLayout.Stretch;
(this.Owner as Form1).mainBackground.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
Then on the load event on the main form, it checks if the file "CurrentWallpaper.png" exists. If it does exist it sets the wallpaper but if you try to change the wallpaper it will get with an error.
"System.IO.IOException: 'The process cannot access the file 'C:\Users\mc_jgeorgio20\Documents\DesktopReborn\CurrentWallpaper.png' because it is being used by another process.'
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\DesktopReborn\\CurrentWallpaper.png"))
{
BackgroundImageLayout = ImageLayout.Stretch;
mainBackground.SizeMode = PictureBoxSizeMode.StretchImage;
BackgroundImage = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\DesktopReborn\\CurrentWallpaper.png");
mainBackground.Image = BackgroundImage;
}
else
{
BackgroundImage = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\DesktopReborn\\DefaultWallpaper.jpg");
}
I've tried this many times and cannot figure out how to set the PictureBox image what am I doing wrong!
Image img;
using (var bmpTemp = new Bitmap(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\DesktopReborn\\CurrentWallpaper.png"))
{
img = new Bitmap(bmpTemp);
mainBackground.Image = img; //mainBackground is the picturebox
}