简体   繁体   中英

System.ObjectDisposedException with graphics object

I have to write a game in C# using a Windows form. For my drawing method on my screen, I'm getting a weird System.ObjectDisposedException which spawns upon one of my graphics objects being instantiated.Here is the problematic code:

// 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.           
    }                       
}

The problematic line, which throws a System.ObjectDisposedException is the line: using (backbufferObject = this.CreateGraphics()) . I'm not sure why this exception is being thrown at this particular point due to the fact that this object is being reinstantiated at this point, whereas it was disposed at the end of the using brackets. So far I've tried putting those two lines in using statements due to the fact that they are affected by IDisposable.

It'd probably be noteworthy that the error is being thrown after I close the Windows form during Run time. So why is this Graphics object being disposed of in this particular instance?

Full code: http://pastebin.com/mSa6XCpP

If your form has been disabled, the this referenced in the line of code the exception happens on:

using (backbufferObject = this.CreateGraphics())

... will like already be disposed. So it isn't the Graphics object that's being disposed. It's the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM