2016-04-17 40 views
-1

我在我的應用程序有問題。我有2個winform並從窗體1調用函數到表單2中的函數來打印web瀏覽器,但是工作量很大。 這裏我的代碼:vb.net使用System.Threading.Thread打電話打印網絡瀏覽器dost工作

形式1:

Dim th As System.Threading.Thread = New Threading.Thread(AddressOf Task_A) 
th.SetApartmentState(ApartmentState.STA) 
th.Start() 

Public Sub Task_A 
    Call form2.fishsefaresh() 
End Sub 

窗口2:

Public Sub fishsefaresh() 
Dim fac As String = " HTML CODE " 
Dim FILE_NAME As String = "my_app.html" 
Dim objWriter As New System.IO.StreamWriter(FILE_NAME) 
objWriter.Write(fac) 
objWriter.Close() 

Dim we As WebBrowser = Form2.WebBrowser1 
we.Navigate("file:///" & IO.Path.GetFullPath(".\my_app.html") 

While we.ReadyState <> WebBrowserReadyState.Complete 
Application.DoEvents() 
End While 

we.Print() 

當我運行的應用程序沒有什麼happend(我設置在我的電腦打印機divise和inestall),我的事情網頁瀏覽器有使用System.Threading時出現問題。

回答

0

使用Application.DoEvents()是不是一個好主意,我不明白爲什麼你甚至會做到這一點時,你已經在後臺線程?

我建議你做的是刪除循環調用DoEvents(),而是訂閱WebBrowser的DocumentCompleted事件。你可以再次取消訂閱,這會導致它只會被提升一次。

更換這一切:

Dim we As WebBrowser = Form2.WebBrowser1 
we.Navigate("file:///" & IO.Path.GetFullPath(".\my_app.html") 

While we.ReadyState <> WebBrowserReadyState.Complete 
Application.DoEvents() 
End While 

we.Print() 

有了這個:

Dim we As WebBrowser = Form2.WebBrowser1 

AddHandler we.DocumentCompleted, AddressOf WebBrowser_DocumentCompleted 

we.Navigate("file:///" & IO.Path.GetFullPath(".\my_app.html") 

然後聲明事件訂閱方法:

Private Sub WebBrowser_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) 
    Dim wb As WebBrowser = DirectCast(sender, WebBrowser) 'Cast the control that raised the event to a WebBrowser. 

    wb.Print() 'Print the page. 
    RemoveHandler wb.DocumentCompleted, AddressOf WebBrowser_DocumentCompleted 'Remove the event subscription. 
End Sub 

希望這有助於!