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;
}
- make a directory named background where your exe located.
- copy background jpg file in that directory
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.
精彩评论