[英]How to change a PictureBox image from another Form
I want to open form2
while form1
loads.我想在
form1
加载时打开form2
。 Also, I want to change the Image of a PictureBox in form2
when an action is triggered in form1
.另外,我想在
form1
中触发动作时更改form2
中 PictureBox 的图像。
To open form2
while form1
loads I used this code:要在加载
form1
时打开form2
,我使用了以下代码:
private void MONITOR3_Load(object sender, EventArgs e)
{
MONITOR4 mo4 = new MONITOR4(this);
mo4.Show();
}
To change the Image of the PictureBox in form2
I used this code, which is must to be run after a condition is met:要更改
form2
中 PictureBox 的图像,我使用了这段代码,它必须在满足条件后运行:
if (textBox1.Text == @"QUEBEC - ALPHA - TANGO - ALPHA - ROMEO - ")
{
MONITOR4 mo4 = new MONITOR4(this);
mo4.pictureBox1.Image = Image.FromFile("D:/QResources/images/HIA.jpg");
}
There are two problems with your current code:您当前的代码有两个问题:
public
, you shouldn't and it's not necessary.public
,但您不应该也没有必要。 A Form is a class like any other in this aspect: create a public method on the Form that provides means to modify a private property, without directly exposing a Control's property to direct access. Here, I'm creating a reference to Monitor4
in the Monitor3
Form:在这里,我在
Monitor3
表单中创建了对Monitor4
的引用:
Monitor4 mo4 = null;
This reference will be use to call a public method ( UpdatePictureBox
) of Monitor4
.该引用将用于调用
Monitor4
的公共方法 ( UpdatePictureBox
)。
Monitor3
Form: Monitor3
形式:
(I'm using the TextChanged
event of a TextBox to select the Image to show in the Monitor4
PictureBox. Of course, it could be the Validate
event or anything else that agrees with your design) (我正在使用 TextBox 的
TextChanged
事件来选择要在Monitor4
PictureBox 中显示的图像。当然,它可以是Validate
事件或与您的设计一致的任何其他事件)
public partial class Monitor3 : Form
{
Monitor4 mo4 = null;
private void Monitor3_Load(object sender, EventArgs e)
{
mo4 = new Monitor4();
//Show Monitor4 on the right side of this Form
mo4.Location = new Point(this.Right + 10, this.Top);
mo4.Show(this);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string newText = textBox1.Text;
switch (newText) {
case "[Some text 1]":
mo4.UpdatePictureBox(@"[Images1 Path]");
break;
case "QUEBEC - ALPHA - TANGO - ALPHA - ROMEO - ":
mo4.UpdatePictureBox(@"[Images2 Path]");
break;
case "[Some text 3]":
mo4.UpdatePictureBox(@"[Images3 Path]");
break;
}
}
}
Monitor4
Form: Monitor4
表格:
public partial class Monitor4 : Form
{
public void UpdatePictureBox(string imagePath)
{
if (File.Exists(imagePath)) {
pictureBox1.Image?.Dispose();
pictureBox1.Image = Image.FromFile(imagePath, true);
}
}
}
Sample result:示例结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.