2013-07-12 51 views
0

問題得到鏈接是多線程是不是正從webbrowser1.document.links鏈接正常工作。我怎麼解決這個問題?多線程對於來自Webbrowser1.Document

Public Class Form1 


Dim thread1 As System.Threading.Thread 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    thread1 = New System.Threading.Thread(AddressOf GetLinks) 
    thread1.Start() 

End Sub 
Private Sub GetLinks() 
    For i As Integer = 0 To WebBrowser1.Document.Links.Count - 1 
     If TextBox1.Text.Length > 0 Then 
      TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(i).ToString 
     Else 
      TextBox1.Text = WebBrowser1.Document.Links(i).ToString 

     End If 
    Next 
End Sub 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    WebBrowser1.Navigate("www.google.com") 
    Me.CheckForIllegalCrossThreadCalls = False 

End Sub 
End Class 
+0

你得到一個錯誤?或沒有獲取數據?或者文本框沒有更新? –

+0

你嘗試在線程中運行它,而不是開始一個新的線程測試的代碼?換句話說,就是在GetLinks的問題,或者甚至沒有被執行Getlinks? –

回答

0

你不能使窗體上的控件之一的調用(在這種情況下,TextBox1中和WebBrowser1)從不是形式的主線程其它另一個線程。您需要使用委託。

這將這樣的伎倆:

Private _iLinks As Integer 

    Dim thread1 As System.Threading.Thread 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     CheckForIllegalCrossThreadCalls = False 
     _iLinks = WebBrowser1.Document.Links.Count 
     thread1 = New System.Threading.Thread(AddressOf GetLinks) 
     thread1.Start() 
    End Sub 

    Private Sub GetLinks() 
     For i As Integer = 0 To _iLinks - 1 
      UpdateTextBoxDelegate(i)    
     Next 
    End Sub 

    Private Sub UpdateTextBox(ByVal iLink As Integer) 
     If TextBox1.Text.Length > 0 Then 
      TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(iLink).ToString 
     Else 
      TextBox1.Text += WebBrowser1.Document.Links(iLink).InnerText.ToString() 
     End If 
    End Sub 

    Private Delegate Sub UpdateTextBoxCallback(ByVal iLink As Integer) 

    Private Sub UpdateTextBoxDelegate(ByVal iLink As Integer) 
     Try 
      If Me.InvokeRequired Then 
       Dim cb As New UpdateTextBoxCallback(AddressOf UpdateTextBox) 
       Me.Invoke(cb, New Object() {iLink}) 
      Else 
       UpdateTextBox(iLink) 
      End If 
     Catch ex As Exception 
      MessageBox.Show("There was an error " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
     End Try 
    End Sub 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     WebBrowser1.Navigate("http://stackoverflow.com/") 
    End Sub 
+0

謝謝大哥回答 – user2573005

+0

@ user2573005 Np個。如果這對你有用,你能把它標記爲正確的答案嗎? – rwisch45