如何共享事件处理程序?

How can I share an event handler?

private void ExitAndSave(object sender, EventArgs e) { foreach(MdiChildren 中的表单) { 如果(表单是 TextForm tf) { tf.BringToFront(); DialogResult dr = MessageBox.Show("Do you want to save your document?", "Save document?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dr == DialogResult.Yes)
                {
                    //counter++;
                    var textBoxValue = tf.FetchTextBoxValue();
                    //string filePath = $"{DateTime.Now.Ticks.ToString()}.txt";
                    string filePath = $"composition{DateTime.Now.Ticks.ToString()}.txt";
                    File.WriteAllText(filePath, textBoxValue);
                }
                if (dr == DialogResult.No)
                {
                    continue;
                }

            }
            else if (form is ImageDocumentForm)
            {
                MessageBox.Show("Please note that only text documents can be saved.", "Advisory:", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }
        Close();
    }

这段代码工作正常。我需要在用户退出程序时调用它。我无法将此事件分配给设计视图中的表单关闭事件。

您的事件参数需要采用 FormClosingEventArgs e 的形式 更改并重试。