2013-12-10 42 views
0

我必須用C#編寫一個使用Windows窗體的遊戲。對於我的屏幕上我的繪製方法,我發現了一個奇怪的System.ObjectDisposedException其產卵在我的圖形對象之一是instantiated.Here是有問題的代碼:帶圖形對象的System.ObjectDisposedException

// Graphics variables. 
Graphics graphics; 
Graphics backBufferObject; 
Bitmap backBuffer; 
// Graphics and backBuffer are instantiated, elsewhere, in the constructor. 

private void DrawScreen() 
{ 
    // Copy the BackBuffer to Graphics Object. 
    using (graphics = Graphics.FromImage(backBuffer)) 
    using (backBufferObject = this.CreateGraphics()) 
    { 
     // Draw BackBuffer to screen (buffer switching).     
     backBufferObject.DrawImage(backBuffer, 0, 0, this.Width, this.Height); 

     graphics.DrawImage(Properties.Resources.scary_pacman, new Rectangle(
      this.Width/2 , this.Height/2, 32, 32)); 

     graphics.Clear(Color.Thistle); // Clear BackBuffer for efficient rendering.   
    }      
} 

有問題的線,這將引發系統。 ObjectDisposedException是行:using (backbufferObject = this.CreateGraphics())。我不確定爲什麼這個例外是在這個特定的點上拋出的,因爲這個對象在這一點上被重新實例化,而它被放置在使用括號的末尾。到目前爲止,我已經嘗試將這兩行放在using聲明中,因爲它們受IDisposable影響。

它可能值得注意的是,錯誤正在拋出我在運行時關閉Windows窗體。那麼爲什麼這個Graphics對象在這個特定的例子中被拋棄?

全碼:http://pastebin.com/mSa6XCpP

回答

1

如果表單已被禁用,在代碼行中引用的this例外發生在:

using (backbufferObject = this.CreateGraphics()) 

...會喜歡已經被佈置。所以它不是正在處理的Graphics對象。這是形式。