I know this question has been asked too many times here but I don't seem to get it fixed so I am posting a new one.
I have two forms Form1 and Form2. Form2 is displayed as an overlay on form1 by setting its topmost property to true. I have a class that does the processing thing for form1 and if the required value is found it opens the form2 in STA thread as an overlay on form1 .
However class processing is a continous process if the value is not found for few next seconds then I need to close the already opened form2 which I am unable to do at the moment due to above exception.
Here is my code:
private void runBrowserThread(bool markerFound)
{
try
{
var th = new Thread(() =>
{
if (markerFound == true)
{
if (Application.OpenForms.OfType<webForm>().Count() == 0)
{
webForm frm = new webForm();
frm.Show();
}
Application.Run();
}
else
{
if (Application.OpenForms.OfType<webForm>().Count() == 1)
{
Form fc = Application.OpenForms["webForm"];
if (fc != null)
fc.Close(); //**This line causes cross thread exception**
}
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
} catch (Exception)
{
//...
}
}
Any suggestions would be really appreciated.