开发者

How to dynamically change backgroundimage in C#.Net?

开发者 https://www.devze.com 2023-03-12 18:28 出处:网络
Now I\'m trying to change dynamically MainForm\'s backgroundimage. I wrote that following code segment...

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

this.BackgroundImage = Image.FromFile("Bar1.png"); this.BackgroundI开发者_如何学CmageLayout = 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?


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)); 


You can get application startup path with this code:

Application.StartupPath + "\yourimage"

or you can use

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


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;


OpenFileDialog dialog = new OpenFileDialog();

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


  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消