![](/img/trans.png)
[英]Change values of dynamically added controls in winform c#.net application, how to track dynamically added controls
[英]How to dynamically change backgroundimage in C#.Net?
现在我正在尝试动态更改 MainForm 的背景图像。 我写了以下代码段......
this.BackgroundImage = Image.FromFile("Bar1.png"); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
我要更改的图像位于我当前的项目中。 但是我不知道如何使用 FromFile 方法?
尝试这样的事情:
string path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
string filename="yourfilename";
this.BackgroundImage = Image.FromFile(Path.Combine(path ,filename));
或者:
string customPath = "d:\testpath";
string filename="yourfilename";
this.BackgroundImage = Image.FromFile(Path.Combine(customPath ,filename));
您可以使用以下代码获取应用程序启动路径:
Application.StartupPath + "\yourimage"
或者你可以使用
System.Reflection.Assembly.GetExecutingAssembly().Location + "\yourimage";
请在此处阅读有关 FromFile 方法的文档。
如果您的资源文件中有图像,您可以像这样访问它:
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;
}
在表单加载事件中添加以下内容
字符串路径 = System.IO.Directory.GetCurrentDirectory() + "\background\"; 字符串文件名="back.jpg"; this.BackgroundImage = Image.FromFile(Path.Combine(path, filename));
如果您更改了保持相同文件名的背景 jpg 文件,则背景将被更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.