c# - C# 方法更改“图片框”
问题描述
试图更改“图片框”中的图像。但不会工作。没有错误,警告。
我有两种形式,一种是“消息框”,一种是主窗体。如果我尝试从另一种方法更改图像(例如:Form1_load)它可以工作。
表格1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1;
namespace jatek
{
public partial class Form1 : Form
public void Eldontesboss(short adat)
{
MessageBox.Show("Number:" + adat); //this is appears,but ...
box.Image = WindowsFormsApp1.Properties.Resources.alap; //this is not work.
}
}
}
表格2:
using jatek;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
private void button1_Click(object sender, EventArgs e)
{
Form1 foo = new Form1();
foo.Eldontesboss(1);
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 foo = new Form1();
foo.Eldontesboss(2);
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
Form1 foo = new Form1();
foo.Eldontesboss(3);
this.Close();
}
}
}
更改 PictureBox 图像。
解决方案
您正在创建的实例Form1
永远不会显示;它们在记忆中是不可见的。如果要更改当前显示的 PictureBox 中的图像,Form1
则需要对该特定实例的引用。从您的描述中不清楚哪种形式是“主要”形式,哪种形式是“消息”形式,但我认为 Form1 是主要形式,而 Form2 是消息。此外,我假设 Form1 正在创建 Form2 的一个实例。如果是这种情况,传递引用的一种方法是Owner
在调用时设置属性Show()
,如下所示:
// ... in Form1, when Form2 is created ...
Form2 f2 = new Form2();
f2.Show(this); // pass reference to Form1, into Form2
现在,在 Form2 中,您可以将Owner
属性转换回类型Form1
并使用它:
// ... in Form2, after being displayed with `Show(this)` back in `Form1` ...
private void button1_Click(object sender, EventArgs e)
{
Form1 foo = (Form1)this.Owner;
foo.Eldontesboss(1);
this.Close();
}
推荐阅读
- parameter-passing - Azure Table storage to Azure Table storage using Azure Data Factory using DateTime Parameterized query
- java - 在 JavaEE Maven 项目中使用 Hibernate 时出现“java.lang.NoClassDefFoundError: javax/persistence/criteria/Selection”错误
- c# - 你如何检测 On MessageActivityAsync 中的活动对话框
- javascript - mongodb changestream“管道”不起作用
- javascript - Codewars 挑战 - Hamelin 的聋鼠 - JavaScript - 如何通过特定字符集拆分字符串?
- graphql - 意外
: 一个graphql文件可以只导入其他文件而不做其他事情吗? - c - 将 BIGNUM 转换为原始二进制文件
- bash - 为什么在本地通过 SSH 初始化远程 bash 脚本时无法访问 GitHub?
- c++ - 在数组中显示第一个元素用户输入
- compiler-construction - 如何在coq中分析两个看似等效但行为不同的程序?