簡體   English   中英

System.ObjectDisposedException與圖形對象

[英]System.ObjectDisposedException with graphics object

我必須使用Windows窗體以C#編寫游戲。 對於屏幕上的繪制方法,我得到一個奇怪的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.           
    }                       
}

有問題的行(拋出System.ObjectDisposedException)是該行: using (backbufferObject = this.CreateGraphics()) 我不確定為什么在這一特定時刻拋出此異常,因為在這一點上實例化了該對象,而將其放置在使用方括號的末尾。 到目前為止,由於它們受到IDisposable的影響,因此我嘗試將這兩行放入using語句中。

可能值得注意的是,在運行時關閉Windows窗體 ,將引發錯誤。 那么為什么在這個特定實例中處理此Graphics對象呢?

完整代碼: http//pastebin.com/mSa6XCpP

如果您的表單已被禁用,則在發生以下情況的代碼行中引用this

using (backbufferObject = this.CreateGraphics())

...將會被處置。 因此,不會處理Graphics對象。 這是表格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM