I'm currently writing a program and stumbled across the following problem:
I want to poll the title of a frame of a website (and react if it changes). Therefore I created a thread. But everytime I try to access the the frame count or frame title I get this InvalidCastException. But outside the thread I can access it without any problems. I tried alot of things but nothing worked. Here is the relevant current code (with some of my tries):
public partial class Form1 : Form
{
bool tmp = true;
public Form1()
{
void webBrowser1_StatusTextChanged(object sender, EventArgs e)
{
private void pollFrameTitle()
{
}
public Form1()
{
InitializeComponent();
webBrowser1.Url = new Uri("http://mysite");
webBrowser1.StatusTextChanged += new EventHandler(webBrowser1_StatusTextChanged);
}
webBrowser1.Url = new Uri("http://mysite");
webBrowser1.StatusTextChanged += new EventHandler(webBrowser1_StatusTextChanged);
void webBrowser1_StatusTextChanged(object sender, EventArgs e)
{
if (webBrowser1.Document.Window.Frames.Count > 2 && tmp == true) //no exception here...
{
}
{
Thread t1 = new Thread(new ThreadStart(pollFrameTitle));
t1.Start();
tmp = false;
}
t1.Start();
tmp = false;
private void pollFrameTitle()
{
Thread.Sleep(500);
int cnt = webBrowser1.Document.Window.Frames.Count; //InvalidCastException (the method returns int)
if (cnt > 2)
}
int cnt = webBrowser1.Document.Window.Frames.Count; //InvalidCastException (the method returns int)
if (cnt > 2)
listBox1.Items.Add(webBrowser1.Document.Window.Frames[2].Document.Title.Equals(Convert.ToString("Title
"))); //writes in a list (for testing) if the title of the page is what
I'm looking for. If I uncomment the int cnt =... above I get the
InvalidCastException here
Does anyone know the reason why this is happening Thanks for any answer!

InvalidCastException, but just in thread
Alessandro Moacyr Duarte
wait for the last document DocumentComplete event (not possible without accessing native interface, though).
suggest reading
Understanding Classic COM Interoperability With .NET Applications
gajar
Andrei G.
enric vives
Sean Reilly
SquadShun
what you need is to handle the DWebBrowserEvents2.OnTitleChange event. If you are using the .Net WebBrowser control, you may need to sink the native interfaces
Lbo