2017-02-21 15 views
0

这里是我的代码需要关于此错误的解释“指定的转换无效”。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     'BackgroundWorker1.RunWorkerAsync() 
     myFunction() 
    End Sub 

    Private Sub myFunction() 
     WebBrowser1.Navigate("http://google.com") 
     While WebBrowser1.ReadyState <> WebBrowserReadyState.Complete 
      Application.DoEvents() 
     End While 
     TextBox1.Text = WebBrowser1.Document.Body.OuterText.ToString 
    End Sub 

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
     myFunction() 
    End Sub 

当我运行这一点,并单击它工作正常Button1的,但是当我在我的按钮1改成这样:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     BackgroundWorker1.RunWorkerAsync() 
    End Sub 

我得到这个错误消息“指定的投是无效”

这里我的目标很简单
1.点击一个按钮,载入页面
2.等待加载页面补偿letely
3.然后抓住页面

+4

你不能直接从一个BackgroundWorker或其他螺纹类型中访问窗体控件​​。为什么不只是使用WebBrowser1.DocumentCompleted事件? –

+0

我可以使用此Control.CheckForIllegalCrossThreadCalls = False代码来访问表单控件,但我的问题是为什么我不能这样做。任何解释? – user2932692

+5

BGW的要点是在后台执行一些长时间运行的任务,使UI响应。 ReportProgress方法允许BGW在需要时将信息发送回UI。 'CheckForIllegalCrossThreadCalls = False'不是答案。这些都不需要 - 页面加载时会触发一个事件 – Plutonix

回答

1

像已经建议,你应该使用Web浏览器控件的DocumentCompleted event,以确定何时页面完全加载的outerText。 Application.DoEvents() is bad,不应该用来保持你的UI响应!

我不知道你的代码最初来自哪里,也不知道为什么这么多人使用它,但它是坏习惯!

正确的做法是使用DocumentCompleted事件:

Private Sub myFunction() 
    WebBrowser1.Navigate("http://google.com") 
End Sub 

Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted 
    If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then 
     TextBox1.Text = WebBrowser1.Document.Body.OuterText 'No need to call ToString() since 'OuterText' already is a string. 
    End If 
End Sub 

此外,跳过BackgroundWorker。无论如何您都无法从后台线程访问WebBrowser,而无需调用UI线程。


巧合的是,我回答a similar question仅仅几个小时前...

相关问题