Well, i have a form which contains 5 WebBrowser
controls each opens a page and handle DocumentComplete
event, The problem is sometimes events don't fire. After reading i came across an answer saying that if the thread is busy the events like Navigated
, DocumentComplete
won't fire so i tried to create the WebBrowser
in a separate thread then add it to the form which results in a cross thread exception
Code
new Thread(() =>
{
WebBrowser1 = new WebBrowser
{
Location = new Point(15, 14),
MinimumSize = new Size(20, 20),
Name = "WebBrowser1",
ScriptErrorsSuppressed = true,
Size = new Size(250, 370),
TabIndex = 0,
Url = new Uri("", UriKind.Relative)
};
((WebBrowser_V1) WebBrowser1.ActiveXInstance).NewWindow += (string u, int f, string n, ref object d, string h, ref bool p) =>
{
p = true;
WebBrowser1.Navigate(u);
};
WebBrowser1.DocumentCompleted += async (sender, args) =>
{
// Code...
};
WebBrowser1.Navigated += (sender, args) =>
{
// Code...
};
WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);
//Cross-Thread Exception
base.Invoke(new MethodInvoker(() =>
{
Controls.Add(WebBrowser1);
}));
Application.Run();
}) {ApartmentState = ApartmentState.STA}.Start();
I need the WebBrowser
control to be visible in the form yet be able to intercept all triggered events.
Edit: if i invoke WebBrowser
i get Controls created on one thread cannot be parented to a control on a different thread
exception.