2009-07-13 42 views
1

我在這裏找到了一個winform的代碼:http://www.wincustomize.com/articles.aspx?aid=136426&c=1如何在Web應用程序中使用System.Windows.Forms.WebBrowser?

而且它可以很好地作爲winform工作。但我想在一個Web應用程序中運行代碼。

  1. 我System.Windows.Forms的和引用Microsoft.mshtml.dll在C加:\ Program Files文件\ Microsoft.NET \主互操作程序集\我的web應用程序。

  2. 我將WebPageBitmap.cs複製到我的Web應用程序中。

  3. 我將Program.cs的Main()作爲Button_Click()複製到我的web應用程序中。

  4. 當我點擊我的web應用程序中的按鈕。它發生錯誤:

ActiveX控件「{8856F961-340A-11D0-A96B-00c04fd705a2」不能被實例化,因爲當前線程不是在一個單一的線程單元。

如何在Web應用程序中使用System.Windows.Forms.WebBrowser來獲取網站縮略圖?

public partial class Capture01 : System.Web.UI.Page 
{ 
    public delegate void WebBrowserDocumentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e); 

    [STAThread] 
    protected void Button1_Click(object sender, EventArgs e) 
    {   
     int width = 1024; 
     int height = 900; 

     int thumbwidth = width; 
     int thumbheight = height;   

     string fileName = "image01.jpg"; 
     string url = "http://www.iweixtest.cn/WE/Site/1647/index.aspx";   
     thumbwidth = 150; 
     thumbheight = 100; 

     //WebPageBitmap webBitmap = new WebPageBitmap(args[0], width, height, false, 10000); 
     WebPageBitmap webBitmap = new WebPageBitmap(url, width, height, false, 10000); 
     if (webBitmap.IsOk) 
     { 
      webBitmap.Fetch(); 
      Bitmap thumbnail = webBitmap.GetBitmap(thumbwidth, thumbheight); 
      //thumbnail.Save(args[1], ImageFormat.Jpeg); 
      thumbnail.Save(fileName, ImageFormat.Jpeg); 
      thumbnail.Dispose(); 
     } 
     else 
     { 
      MessageBox.Show(webBitmap.ErrorMessage); 
     }  
    } 
} 

WebPageBitmap.cs

namespace GetSiteThumbnail 
{ 
    /// <summary> 
    /// Thanks for the solution to the "sometimes not painting sites to Piers Lawson 
    /// Who performed some extensive research regarding the origianl implementation. 
    /// You can find his codeproject profile here: 
    /// http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=39324 
    /// </summary> 
    [InterfaceType(1)] 
    [Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")] 
    public interface IHTMLElementRender2 
    { 
     void DrawToDC(IntPtr hdc); 
     void SetDocumentPrinter(string bstrPrinterName, ref _RemotableHandle hdc); 
    } 

    /// <summary> 
    /// Code by Adam Najmanowicz 
    /// http://www.codeproject.com/script/Membership/Profiles.aspx?mid=923432 
    /// http://blog.najmanowicz.com/ 
    /// Some improvements suggested by Frank Herget 
    /// http://www.artviper.net/ 
    /// </summary> 
    class WebPageBitmap 
    { 
     private WebBrowser webBrowser; 
     private string url; 
     private int width; 
     private int height; 
     private bool isOk; 
     private string errorMessage; 

     public string ErrorMessage 
     { 
      get { return errorMessage; } 
     } 

     public bool IsOk 
     { 
      get { return isOk; } 
      set { isOk = value; } 
     } 

     public WebPageBitmap(string url, int width, int height, bool scrollBarsEnabled, int wait) 
     { 
      this.width = width; 
      this.height = height; 

      this.url = 
       url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ? 
       url : this.url = "http://" + url; 

      try 
      // needed as the script throws an exeception if the host is not found 
      { 
       HttpWebRequest req = (HttpWebRequest)WebRequest.Create(this.url); 
       req.AllowAutoRedirect = true; 
       //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"; //成功 
       req.UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 
       //req.Referer = "http://www.cognifide.com"; 
       req.ContentType = "text/html"; 
       req.Accept = "*/*"; 
       req.KeepAlive = false; 

       using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) 
       { 
        string x = resp.StatusDescription; 
       }  
      } 
      catch (Exception ex) 
      { 
       errorMessage = ex.Message; 
       isOk = false; 
       return; 
      } 
      isOk = true;              // public, to check in program.cs if the domain is found, so the image can be saved 

      webBrowser = new WebBrowser(); 
      webBrowser.DocumentCompleted += 
      new WebBrowserDocumentCompletedEventHandler(documentCompletedEventHandler); 
      webBrowser.Size = new Size(width, height); 
      webBrowser.ScrollBarsEnabled = false; 
     } 

     /// <summary> 
     /// Fetches the image 
     /// </summary> 
     /// <returns>true is the operation ended with a success</returns> 
     public bool Fetch() 
     { 
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 
      req.AllowAutoRedirect = true; 
      //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"; 
      req.UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 
      //req.Referer = "http://www.cognifide.com"; 
      req.ContentType = "text/html"; 
      req.AllowWriteStreamBuffering = true; 
      req.AutomaticDecompression = DecompressionMethods.GZip; 
      req.Method = "GET"; 
      req.Proxy = null; 
      req.ReadWriteTimeout = 20; 

      HttpStatusCode status; 
      using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) 
      { 
       status = resp.StatusCode; 
      } 

      if (status == HttpStatusCode.OK || status == HttpStatusCode.Moved) 
      { 
       webBrowser.Navigate(url); 
       while (webBrowser.ReadyState != WebBrowserReadyState.Complete) 
       { 
        Application.DoEvents(); 

       } 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 

     private void documentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e) 
     { 
      ((WebBrowser)sender).Document.Window.Error += 
       new HtmlElementErrorEventHandler(SuppressScriptErrorsHandler); 
     } 

     public void SuppressScriptErrorsHandler(object sender, HtmlElementErrorEventArgs e) 
     { 
      e.Handled = true; 
      MessageBox.Show("Error!"); 
     } 

     internal Bitmap GetBitmap(int thumbwidth, int thumbheight) 
     { 
      IHTMLDocument2 rawDoc = (IHTMLDocument2)webBrowser.Document.DomDocument; 
      IHTMLElement rawBody = rawDoc.body; 
      IHTMLElementRender2 render = (IHTMLElementRender2)rawBody; 

      Bitmap bitmap = new Bitmap(width, height); 
      Rectangle bitmapRect = new Rectangle(0, 0, width, height); 

      // Interesting thing that despite using the renderer later 
      // this following line is still necessary or 
      // the background may not be painted on some websites. 
      webBrowser.DrawToBitmap(bitmap, bitmapRect); 

      using (Graphics graphics = Graphics.FromImage(bitmap)) 
      { 
       IntPtr graphicshdc = graphics.GetHdc(); 
       render.DrawToDC(graphicshdc); 

       graphics.ReleaseHdc(graphicshdc); 
       graphics.Dispose(); 

       if (thumbheight == height && thumbwidth == width) 
       { 
        return bitmap; 
       } 
       else 
       { 
        Bitmap thumbnail = new Bitmap(thumbwidth, thumbheight); 
        using (Graphics gfx = Graphics.FromImage(thumbnail)) 
        { 
         // high quality image sizing 
         gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;        
         gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;                  // make it look pretty 
         gfx.DrawImage(bitmap, new Rectangle(0, 0, thumbwidth, thumbheight), bitmapRect, GraphicsUnit.Pixel); 
        } 
        bitmap.Dispose(); 
        return thumbnail; 
       } 
      } 
     } 
    } 
} 

回答

3

我已成功地在Web應用程序中使用System.Windows.Forms.WebBrowser。

只要按照上述步驟,並在Web窗體頁添加AspCompat =「真」:

感謝您對所有的答案。

0

簡短的回答是,沒有在System.Windows意在web應用中使用。

System.Windows.Forms是客戶端控件。但是,Web應用程序在服務器端運行,並在System.Web.UI中擁有自己的UI元素。

mshtml可能是另一個絆腳石。我真的不能說它是否可以從IIS訪問。

有可能是另一種方式來做到這一點,但我會讓一個知道更多的人比我回答那部分。

3

您可以創建自己的工作線程並調用SetApartmentState將其更改爲STA線程;這個線程可以完成渲染網頁的工作。然而,需要進行大量的線程間通信,正如R.Bemrose所說的,System.Windows類實際上並不是用於Web應用程序內部的。

另一種方法是重寫示例應用程序(作爲.EXE)以獲取兩個參數:(1)要下載的URL和(2)截圖圖像的輸出位置。您的網絡應用程序可以創建一個臨時路徑(對於輸出文件),啓動該程序(使用Process.Start),等待它完成,加載它創建的輸出文件,然後刪除臨時文件,一旦它發送到客戶端或否則不再需要。 (當然,如果出現錯誤,它需要有不同的錯誤處理方式,而不是顯示消息框。)

相關問題