开发者

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.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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜