You need to expose a property in the child forms. Now the MdiParent can check if it is busy.
The easiest way is to use an interface. This way you can have different types of child forms and the interface makes it easy to interrogate.
interface IFormState
{
bool IsBusy { get; }
}
Implementing the Interface on the child form(s):
public partial class Form2 : Form, IFormState
{
public Form2()
{
InitializeComponent();
}
public bool IsBusy { get; private set; }
private void butSetBusyState_Click(object sender, EventArgs e)
{
IsBusy = true;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = IsBusy;
}
}
I have used a button to set the busy state. Also, I've hooked the
FormClosing
event of the child to also prevent it from closing if busy.
Now for the MDI Parent:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var form = new Form2();
form.MdiParent = this;
form.Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (var item in MdiChildren)
{
if (((IFormState)item).IsBusy)
{
e.Cancel = true;
break;
}
}
}
}
Like the child forms, the MDI parent hooks the
FormClosing
event. When fired, will iterate through all the open child forms and cancel the closing if a child form is busy.