2011-10-04 47 views
2

我一直在试图让WebBrowser绘制到XNA 4.0中的纹理,并且我已经找到了关于如何去做的几个指南。问题是当我尝试实现它时,无论是更改Url属性还是致电Navigate(),它都不会加载页面。我有一种感觉,我对所需的线程有点无知,因为我的项目没有作为STA线程启动,所以我创建了一个单独的线程来启动Web浏览器并呈现为位图。Web浏览器在XNA 4.0中没有导航

我是这样开始的:

public void LoadTexture(GraphicsDevice gfx, ContentManager content, string filename, float duration = -1f) 
{ 
    this.gfx = gfx; 
    this.filename = filename; 
    this.duration = duration; 

    _resetEvent = new AutoResetEvent(false); 
    Thread thread = new Thread(GetWebScreenshot); 
    thread.SetApartmentState(ApartmentState.STA); 
    thread.Start(); 
    _resetEvent.WaitOne(); 
} 

而这里的GetWebScreenshot

public void GetWebScreenshot() 
{ 
    this.web = new WebBrowser(); 
    this.web.Size = new Size(gfx.Viewport.Width, gfx.Viewport.Height); 
    this.web.Url = new Uri(this.filename); 

    while (this.web.ReadyState != WebBrowserReadyState.Complete) 
    { 
     if (this.web.ReadyState != WebBrowserReadyState.Uninitialized) 
     { 
      Console.WriteLine(this.web.ReadyState.ToString()); 
     } 
    } 

    bitmap = new Bitmap(this.gfx.Viewport.Width, this.gfx.Viewport.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
    this.web.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height)); 
    this.texture = BitmapToTexture2D(this.gfx, bitmap); 
    _resetEvent.Set(); 
} 

ReadyState物业从来没有从Uninitialized变化,我已经使用了DocumentReady事件也试过,而且永远不会被解雇。我也试过Join()而不是AutoResetEvent,但似乎没有任何工作。

回答

2

我是对的,这是我的无知。关于ActiveX控件和Single Threaded Apartments的关键在于消息队列需要被抽取。所以,现在我已经将我的代码重新编码为以下内容:

public void LoadTexture(GraphicsDevice gfx, ContentManager content, string filename, float duration = -1f) 
{ 
    this.gfx = gfx; 
    this.filename = filename; 
    this.duration = duration; 

    Thread thread = new Thread(GetWebScreenshot); 
    thread.SetApartmentState(ApartmentState.STA); 
    thread.Start(); 
    thread.Join(); 
} 

public void GetWebScreenshot() 
{ 
    this.web = new WebBrowser(); 
    this.web.Size = new Size(gfx.Viewport.Width, gfx.Viewport.Height); 
    this.web.Url = new Uri(this.filename); 
    this.web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted); 
    Application.Run(); // Starts pumping the message queue (and keeps the thread running) 
} 

void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    Bitmap bitmap = new Bitmap(this.gfx.Viewport.Width, this.gfx.Viewport.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
    this.web.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height)); 
    this.texture = HTMLTextureFactoryMachine.BitmapToTexture2D(this.gfx, bitmap); 
    Application.ExitThread(); // Exits the thread 
} 

这可以正常工作。