我会提供一个基于接口的解决方案。如果应用程序可以关闭,您可以通过这种方式轻松管理统一的方式。通过以下实现,父窗体负责询问子窗口是否准备好关闭,子窗体执行必须执行的任何操作并回复主窗口。
假设我有接口IManagedForm
:
interface IManagedForm
{
bool CanIBeClosed(Object someParams);
}
两种形式 (Form1
和ChildForm
) 都会实现它。
请注意,对于此示例,我ChildForm
以这种方式实例化:
ChildForm cf = new ChildForm() { Owner = this, Name = "ChildForm" };
cf.Show();
首先是接口的实现Form1
:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
object someArgsInterestingForTheMethod = new object();
e.Cancel = !((IManagedForm)this).CanIBeClosed(someArgsInterestingForTheMethod);
}
// Ask the ChildForm it is done. If not the user should not leave the application.
public bool CanIBeClosed(object someParams)
{
bool isOKforClosing = true;
var cf = this.Controls["ChildForm"] as IManagedForm;
if (cf != null)
{
isOKforClosing = cf.CanIBeClosed(someParams);
if (!isOKforClosing)
{
MessageBox.Show("ChildForm does not allow me to close.", "Form1", MessageBoxButtons.OK);
}
}
return isOKforClosing;
}
最后你ChildForm
的接口实现看起来像这样:
private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
object someArgsInterestingForTheMethod = new object();
e.Cancel = !((IManagedForm)this).CanIBeClosed(someArgsInterestingForTheMethod);
}
public bool CanIBeClosed(object someParams)
{
// This flag would control if this window has not pending changes.
bool meetConditions = ValidateClosingConditions(someParams);
// If there were pending changes, but the user decided to not discard
// them an proceed saving, this flag says to the parent that this form
// is done, therefore is ready to be closed.
bool iAmReadyToBeClosed = true;
// There are unsaved changed. Ask the user what to do.
if (!meetConditions)
{
// YES => OK Save pending changes and exit.
// NO => Do not save pending changes and exit.
// CANCEL => Cancel closing, just do nothing.
switch (MessageBox.Show("Save changes before exit?", "MyChildForm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
{
case DialogResult.Yes:
// Store data and leave...
iAmReadyToBeClosed = true;
break;
case DialogResult.No:
// Do not store data, just leave...
iAmReadyToBeClosed = true;
break;
case DialogResult.Cancel:
// Do not leave...
iAmReadyToBeClosed = false;
break;
}
}
return iAmReadyToBeClosed;
}
// This is just a dummy method just for testing
public bool ValidateClosingConditions(object someParams)
{
Random rnd = new Random();
return ((rnd.Next(10) % 2) == 0);
}
希望它足够清楚。