【问题标题】:Update data in form 2 without opening a new form2在不打开新的form2的情况下更新form 2中的数据
【发布时间】:2013-03-25 18:49:40
【问题描述】:

我有 2 个表格,From1 和 Form2。通过单击按钮,将图像发送到 Form2 以显示在 Form 2 的图片框中。

每次单击按钮时,都会打开一个新的 Form2 并显示图像,但这不是我想要的。

我希望只更新 Form2 的图片框中的图像,并且只保留一个 Form2(第一次打开的)。

这是我在 Form1 中的代码:

Image<Bgr, byte> imResult =DrawMatches(imColor,Points1, imColorPrv,Points2,Indices, new Bgr(System.Drawing.Color.Yellow), new Bgr(System.Drawing.Color.Red);
Form2 frmDrawMatchPoints = new Form2(imResult);
frmDrawMatchPoints.Show();

这是我在 Form2 中的代码:

Image<Bgr, byte> imResult;
public Form2(Image<Bgr, byte> imResult)
{
    InitializeComponent();
    this.imResult = imResult;
}

private void Form2_Load(object sender, EventArgs e)
{
    picBoxMatches.Image = imResult.ToBitmap();
}

【问题讨论】:

    标签: c# winforms updates


    【解决方案1】:

    您可以向 Form2 添加一个新方法:

    public UpdateImage(Image<Bgr, byte> imResult)
    {
        this.imResult = imResult;
        picBoxMatches.Image = imResult.ToBitmap();
    }
    

    然后在 Form1 中你可以这样做:

    private Form2 form2;   // Some private field
    
    // Inside the event handler
    if (form2 == null)
        form2 = new Form2(imResult);
    else
        form2.UpdateImage(imResult);
    

    【讨论】:

    • 在 Form 1 中,第一次 form2 应该被分配到某个地方: form2 = new Form2(imResult);否则在“if(form2==null)”行我收到错误:错误 4 使用未分配的局部变量
    • @farzinparsa 正如我在代码中指出的那样,form2 应该是一个隐式设置为 null 的字段。如果您的 form2 是该方法的本地变量,这将不起作用,因为一旦方法结束,它将失去其值。
    【解决方案2】:

    把它放到全局范围

    public Form2 frmDrawMatchPoints = new Form2();
    

    在Form2中新建函数,参数相同,预览图片

    public void PreviewPicture(Image<Bgr, byte> imResult)
    {
        this.imResult = imResult;
    }
    

    在 Form1 中你应该只有:

    Image<Bgr, byte> imResult =DrawMatches(imColor,Points1, imColorPrv,Points2,Indices, new Bgr(System.Drawing.Color.Yellow), new Bgr(System.Drawing.Color.Red);
    
    frmDrawMatchPoints.PreviewPicture(imResult);
    frmDrawMatchPoints.Show();
    

    【讨论】:

      猜你喜欢
      • 2014-01-04
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多