I have created a general code module that identifies all forms with a particular title, and then attempts to close them. If changes have been made on the form, a popup modal dialog (form) will appear asking to save, not to save and cancel the changes (yes, no and cancel).
The code below shows my solution. It works well ... but was just wondering if you could recommend a more elegant / software engineered way of coding this?
Code: Select all
private void closeOpenForms()
{
IList<Form> allForms = Host.Local.FindChildren<Form>();
foreach (Form frm in allForms)
{
// close all Property Pages
if (frm.Title.Contains("Properties"))
{
Thread dialogWatcher = new Thread(ClosePopUpDialog);
dialogWatcher.IsBackground = true;
dialogWatcher.SetApartmentState(ApartmentState.STA);
dialogWatcher.Start();
frm.Close();
}
}
}
private void ClosePopUpDialog()
{
while (true)
{
Thread.Sleep(1000);
IList<Form> allForms = Host.Local.FindChildren<Form>();
foreach (Form fm in allForms)
{
if (fm.Title.Contains("Properties"))
{
IList<Button> allButtons = fm.FindChildren<Button>();
foreach (Button b in allButtons)
{
if (b.Text.Equals("&No"))
{
b.Focus();
b.EnsureVisible();
b.Click();
return;
}
}
}
}
return;
}
}