2013-01-23 16 views
0

本質上,我希望我的程序將列表加載到ListBox中,並允許用戶單擊「打印」,它將WebBrowser導航到列表中的每個頁面,然後將它們打印出來全部單獨出來。使用WebBrowser在列表框中打印文檔

但是,它只打印出2頁(在我的例子中,我有4個頁面在列表框中),然後停止,沒有完成循環。 (最有可能是由於WebBrowser控件仍然很忙)

我覺得我在這裏犯了一個簡單的錯誤。任何有關造成這種情況的見解都將不勝感激!

我的代碼:

private void Form1_Load(object sender, EventArgs e) 
{ 
    DirSearch(Application.StartupPath); 
} 

void DirSearch(string sDir) 
{ 
    try 
    { 
     foreach (string d in Directory.GetDirectories(sDir)) 
     { 
      foreach (string f in Directory.GetFiles(d).Select(Path.GetFileName)) 
      { 
       listBox1.Items.Add(f); 
      } 
      DirSearch(d); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    WebBrowser webBrowserForPrinting = new WebBrowser(); 
    webBrowserForPrinting.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocument); 

    foreach (string s in listBox1.Items) 
    { 
     try 
     { 
      webBrowserForPrinting.Url = new Uri(Application.StartupPath + "\\COAForms\\" + s); 
     } 
     catch (Exception) 
     { 
     } 
    } 
} 

private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    // Print the document now that it is fully loaded. 
    ((WebBrowser)sender).Print(); 

} 
+0

代碼看起來不錯,雖然你應該在這個空的捕獲中發佈一條消息 - 我想你可能會壓制這個可能會解決問題的錯誤。 – U1199880

回答

0

與Web瀏覽器控件的一個常見錯誤是試圖使用它在傳統for循環,就像你在這裏。

WebBrowser頁面加載是一個異步操作。這就是爲什麼有一個DocumentCompleted事件。你需要在你的循環中解釋這一點。使DocumentCompleted(例如PrintDocument)處理程序加載下一個位置,而不是使用傳統的for循環。