从表单2更新Form1(主表单)以显示已处理的图像

时间:2013-02-25 16:51:59

标签: c# winforms

我有两个表单,Form1(主表单)和Form2。表单1显示图像文件,pdf转换等。但是如果用户想要查看Zip文件,则调用Form2显示listView上可用的所有Zip文件的预览。如果用户在Form2上选择特定的Zip文件,则解压缩文件并将图像文件发送到Form2。但我不知道如何从Form1刷新Form2。顺便说一下,Form2中的所有图像现在都存在于Form中的变量列表中!显示但表格没有更新。

form2代码:

 private void btn_read_Click(object sender, EventArgs e)
    {

        Form1 f1 = new Form1();
        f1.ReadArchives(Filepath);  //this function creates the image files on Form1
       this.Close(); //close form2

       for (int index = Application.OpenForms.Count - 1; index >= 0; index--)
        {
            if (Application.OpenForms[index].Name == "Form1")
            {
                //Application.OpenForms[index].Close();//EFFECTIVE BUT CLOSES THE WHOLE APPLICATION
               Application.OpenForms[index].Invalidate(); //no effect
                 Application.OpenForms[index].Refresh();//no effect
                Application.OpenForms[index].Update();//no effect
                Application.OpenForms[index].Show();//no effect
            }
        }            

    }

2 个答案:

答案 0 :(得分:0)

您正在代码中实例化新的Form1 - 与您已有的Form1(主要)不同。这就是表格没有更新的原因。

在我的answer中,我展示了基于事件的方法,以在不同形式之间共享变量/对象 - 可以轻松调整它以传输对象集合。希望它有所帮助。

答案 1 :(得分:0)

因此,当您希望父表单在子表单上发生某些事情时执行某些操作时,适当的机制是使用事件。在这种情况下,当我们希望传递信息时,子表单正在关闭,因此我们可以重新使用FormClosed事件。

这使得编写儿童表单非常简单:

public partial class Form2 : Form
{
    public string Filepath {get;set;}

    private void btn_read_Click(object sender, EventArgs e)
    {
        Close();
    }
}

然后父表单可以使用适当的事件来处理其余事件:

public partial class Form1 : Form
{
    private void button1_Click(object sender, EventArgs args)
    {
        Form2 child = new Form2();
        child.FormClosing += (_, arg) => ReadArchives(child.Filepath);
        child.Show();
    }

    private void ReadArchives(string filepath)
    {
        throw new NotImplementedException();
    }
}