Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

c# - "Specified cast is not valid" error

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...