Soge
Soge

Reputation: 1

How to dynamically change backgroundimage in C#.Net?

Now I'm trying to change dynamically MainForm's backgroundimage. I wrote that following code segment...

this.BackgroundImage = Image.FromFile("Bar1.png"); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;

Image that I want to change is located in my current project. But I don't know how to use FromFile Method?

Upvotes: 0

Views: 21881

Answers (5)

Uday Phadke
Uday Phadke

Reputation: 51

  1. make a directory named background where your exe located.
  2. copy background jpg file in that directory
  3. add following in form load event

    string path = System.IO.Directory.GetCurrentDirectory() + "\background\"; string filename="back.jpg"; this.BackgroundImage = Image.FromFile(Path.Combine(path, filename));

if you changed background jpg file keeping same file name, the background will be changed.

Upvotes: -1

Nyabote Nickson
Nyabote Nickson

Reputation: 1

OpenFileDialog dialog = new OpenFileDialog();

if (dialog.ShowDialog() == DialogResult.OK)
{
    this.BackgroundImage = Image.FromFile(dialog.FileName);
    this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
}

Upvotes: -1

danyolgiax
danyolgiax

Reputation: 13086

Try something like this:

string path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );   



string filename="yourfilename";

this.BackgroundImage = Image.FromFile(Path.Combine(path ,filename)); 

or:

string customPath = "d:\testpath"; 

string filename="yourfilename";

this.BackgroundImage = Image.FromFile(Path.Combine(customPath ,filename)); 

Upvotes: 4

Navid Rahmani
Navid Rahmani

Reputation: 7958

You can get application startup path with this code:

Application.StartupPath + "\yourimage"

or you can use

System.Reflection.Assembly.GetExecutingAssembly().Location + "\yourimage";

Upvotes: 2

Renatas M.
Renatas M.

Reputation: 11820

Please read documentation about FromFile method here.

And if you have image in your resource file, you can access it like this:

this.BackgroundImage = Properties.Resources.yourImageName;

Upvotes: 1

Related Questions