[英]System.ObjectDisposedException: Cannot access a disposed object
[英]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.