Reputation: 26611
I'm using this code which is meant to check the text in webBrowser1, although instead I'm getting the error "Specified cast is not valid." for string docText = webBrowser1.Document.Body.InnerText;
. Any ideas why? Could it be because I'm accessing the webBrowser from another thread? Thanks.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string docText = webBrowser1.Document.Body.InnerText;
if (docText == "Hello")
{
MessageBox.Show("Alerted!");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Upvotes: 2
Views: 5189
Reputation: 4856
The .Body section will return an object null reference exception and .innerHTML will not be recognized as a string if you haven't waited for the page to load, it may be triggering that error you are getting as a result. have you done correct waiting for document to load before all this? check out my answers on how to do proper waiting on webbrowser control if you need help with this.
Upvotes: 0
Reputation: 60013
The exception may in fact be caused by accessing the WebBrowser.Document property from a thread that isn't the main UI thread. You can verify that by looking for the following lines in the stack trace of the System.InvalidCastException
:
at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
at System.Windows.Forms.WebBrowser.get_Document()
If this is the case, try passing the content of the web page to the background thread as an argument instead:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var docText = (string)e.Argument;
}
private void timer1_Tick(object sender, EventArgs e)
{
var docText = webBrowser1.Document.Body.InnerText;
backgroundWorker1.RunWorkerAsync(docText);
}
Upvotes: 5
Reputation: 216353
I will try with...
backgroundWorker1.RunWorkerAsync(webBrowser1.Document.Body.InnerText);
this will remove the cast exception
and in DoWork
string docText = e.Argument.ToString();
this will remove the UI thread issue
Upvotes: 2
Reputation: 573
Maybe you should wait for DocumentCompleted event from WebBrowser ctrl before accessing Document.
Upvotes: 0