有没有办法用 C# 调用 Visual Studio 中已经存在的表单的函数

Is there a way to call a function of an already existing form in Visual Studio with C#

有没有一种方法可以调用存在于父表单(用户)中的函数,其中调用了第二个表单的实例(addNewUser)?我想要做的是当第二个表单关闭时,在父表单(用户)中执行一个函数,该函数正在更新 table 以便在第二个表单(addNewUser)中完成的更改在 table 第一种形式(用户)。

a simple drawing of what I am trying to achieve

对于像 WinForms 这样的事件驱动范例,最好的方法是在有事件可以拦截时使用事件。
您可以从创建事件引发器实例的任何 class 订阅事件。在这种情况下,您可以简单地将事件处理程序绑定到第二个表单引发的 FormClosed 事件。

// Suppose you have a button click that opens the second form.
private void button_Click(object sender, EventArgs e)
{
    SecondForm f = new SecondForm();
    f.FormClosed += onSecondFormClosed;
    f.ShowDialog();
}

private void onSecondFormClosed(object sender, FormClosedEventArgs e)
{
    // Do whatever you need to do when the second form closes
}

定义全局变量以标识您的表单实例:

internal static Form1 CurrentForm1 { get; set; }
internal static Form2 Frm2 { get; set; }

则影响变量如下:

  public Form1()
    {
        InitializeComponent();
        CurrentForm1 = this;
    }

在您的代码中的某处,您将定义 Form2:

Frm2 = new Form2();

现在,您将通过 Frm2 代码访问 form1 非静态方法:

Form1.CurrentForm1.UpdateMyThings();

并且从 Frm1 代码,您将能够在 Frm2 上观看内容,例如:

bool notified = false;
while (Frm2.backgroundWorker1.IsBusy)
{
    if (notified == false)
    {
        Message("Please wait...");
        notified = true;
    }
    Application.DoEvents();
}

在这个例子中,Frm1 检查 backgroundworker #1 是否仍在 Frm2 中 运行(Message 函数可能会在标签或其他内容中显示消息)。