インターフェイスに基づいたソリューションを提供します。この方法は、アプリケーションを閉じることができるかどうかを管理するための統一された方法を簡単に持つことができます。次の実装では、親フォームが子ウィンドウに閉じる準備ができているかどうかを尋ね、子は実行する必要のあるアクションを実行し、メインウィンドウに応答します。
私がインターフェースを持っているとしましょう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);
}
それが十分に明確であることを願っています。