【问题标题】:System.ObjectDisposedException with graphics objectSystem.ObjectDisposedException 与图形对象
【发布时间】:2013-12-10 10:11:42
【问题描述】:

我必须使用 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())。我不确定为什么在这个特定的点抛出这个异常,因为这个对象正在被重新实例化,而它被放置在使用括号的末尾。到目前为止,我已经尝试将这两行放在using 语句中,因为它们受到 IDisposable 的影响。

可能值得注意的是,我在运行时关闭 Windows 窗体后引发了错误。那么为什么这个 Graphics 对象会在这个特定的实例中被丢弃呢?

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

【问题讨论】:

    标签: c# graphics


    【解决方案1】:

    如果您的表单已被禁用,则代码行中引用的 this 会发生异常:

    using (backbufferObject = this.CreateGraphics())
    

    ... 就像已经被处理掉了。所以不是 Graphics 正在处理的对象。就是表格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多