Reputation: 1528
I have a winforms C# application with multiple MDI child windows, each of which can contain changed user data.
When a child window is closed individually, the user is warned about the changed data, which works fine.
However, if the user attempts to close the application, I only want to warn once for all child windows if any have changed data (the data is not that critical).
So the idea is to hook into the main window's OnClosing event, look for changed user data in any of the child windows, display a warning just once if I find any changed data, and set a boolean to prevent each child window from bothering the user multiple times.
The problem I'm seeing is, the OnClosing event for the main window is triggered AFTER the OnClosing events for each child window are triggered, so I can't set my boolean soon enough.
Is there an event for application closing that I can hook into that arrives sooner than OnClosing, or is there maybe a Windows message I can trap?
Upvotes: 0
Views: 316
Reputation: 205849
Instead of hooking into MDI parent form close messages and setting flags, you can make your child forms subscribe to FormClosing event and skip the processing if FormClosingEventArgs.CloseReason is MdiFormClosing
:
private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.MdiFormClosing) return; // Do nothing
// ...
}
Upvotes: 2
Reputation: 1006
I would create a boolean in each of your sub-windows that dictates whether or not to open the prompt.
public bool Prompt = true;
private void Form_Closing(object sender, EventArgs e)
{
if (Prompt)
{
MessageBox.Show("Data thingy...whatever");
}
}
And then in your main form you can set this boolean to false.
private void MainForm_Closing(object sender, EventArgs e)
{
form1.Prompt = false;
form1.Close();
form2.Prompt = false;
form2.Close();
//etc
}
Upvotes: 0
Reputation: 1528
Solved it, I just needed to hook into the WM_CLOSE Windows message:
protected override void WndProc(ref Message m)
{
// Crucially, this message arrives before my child windows get the OnClosing event.
if (m.Msg == WM_CLOSE)
{
// So I set my boolean here and everything works great.
}
base.WndProc(ref m);
}
Upvotes: 2