【问题标题】:calling a method from another window form closing event. c# [closed]从另一个窗口窗体关闭事件调用方法。 c# [关闭]
【发布时间】:2014-02-28 17:22:00
【问题描述】:

如何从另一个窗体关闭事件中调用窗体的方法? 假设 second for 正在关闭,我想在 second 关闭时调用第一个窗体的方法以更新第一个窗口窗体上的一些更改。

【问题讨论】:

  • 你尝试了吗?您用ShowShowDialog 方法打开第二个表单?

标签: c# .net winforms c#-4.0 window


【解决方案1】:

您可以在第一个表单中为form_closing 事件添加事件处理程序并进行相应处理。

form1某处

form2.Form_Closing += yourhandler;

【讨论】:

  • 不,实际上我试图在第二个表单关闭时调用第一个表单的调用方法。
  • @AmritPal 正是这是做什么的。
  • @AmritPal Steve 的解决方案会奏效。如果您将上述代码放在第一个表单中,它将在第二个表单关闭时调用
  • @AmritPal form_closing 事件将在第二个表单关闭时触发,因此如果您在第一个表单中侦听该事件,则每当第二个表单关闭时都会调用事件处理程序方法。在事件处理程序中,您可以调用任何方法来进行您想要的更新
  • thnku Steve,你的解决方案工作:)
【解决方案2】:

这里假设表单 2 有一个名为 TextBox1 的控件,当表单 2 关闭时,将调用 lambda 表达式并将数据传输到表单 1。

public partial class Form1 : Form
{

    private Form2 openedForm2 = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Not sure if you would want more than 1 form2 open at a time.
        if (this.openedForm2 == null)
        {
            this.openedForm2 = new Form2();
            //Here is your Event handler which accepts a Lambda Expression, code inside is performed when the form2 is closed.
            this.openedForm2.FormClosing += (o, form) =>
            {
                // this is Executed when form2 closes.
                // Gets text from Textbox1 on form2 and assigns its value to textbox1 on form 1
                this.textBox1.Text = ((Form2)o).Controls["TextBox1"].Text;
                // Set it null so you can open a new form2 if wanted.
                this.openedForm2 = null;
            };
            this.openedForm2.Show();
        }
        else 
        {
            // Tells user form2 is already open and focus's it for them.
            MessageBox.Show("Form 2 is already open");
            this.openedForm2.Focus();
        }
    }
}

【讨论】:

    【解决方案3】:

    将第一个表单中的引用传递给第二个表单。假设您以这种方式创建第二个表单(从您的第一个表单开始):

    Form2 frm2 = new Form2();
    frm2.referenceToFirstForm = this
    

    在你的第二种形式中,你应该有这个:

    public Form1 referenceToFirstForm
    

    然后在您的OnClosing 事件中您可以引用referenceToFirstForm

    【讨论】:

    • 当您可以正确使用事件并将事件附加到应该处理的位置而不是从定义它的类中。
    • 只是提供选项。史蒂夫的解决方案更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多