什么时候是System.Drawing.Bitmap而不是System.Drawing.Bitmap
本文关键字:Bitmap System Drawing 什么时候 | 更新日期: 2023-09-27 18:05:09
在拍摄内存扩展问题时,我遇到了一个异常,使我难住了。
using (var theImage = ApplicationGlobalWinForm.Properties.Resources.LanguageIcon) {
PictureBox1.Image = theImage;
this.Icon = System.Drawing.Icon.FromHandle(theImage.GetHicon());
}
,
-
ApplicationGlobalWinForm.Properties.Resources.LanguageIcon
是一个资源驻留映像,它作为System.Drawing.Bitmap
加载 -
this.Icon
是应用程序窗口的图标 -
PictureBox1
是客户区图像 - 这个应用程序是一个WinForms(而不是WPF)应用程序,正如这篇文章的标签
using
是我寻找内存扩展问题的一部分保存上述代码的方法完成后,应用程序遇到"类型为'System '的未处理异常"。.
将PictureBox1.Image
赋值移到代码的更深处,并将其赋值为theIcon.ToBitmap()
而不是theImage
来修复问题:
using (var theImage = ApplicationGlobalWinForm.Properties.Resources.LanguageIcon) {
var theIcon = System.Drawing.Icon.FromHandle(theImage.GetHicon());
this.Icon = theIcon;
PictureBox1.Image = theIcon.ToBitmap();
}
假设theImage
和theIcon.ToBitmap
都是同一类型(System.Drawing.Bitmap
),发生了什么?
更令人困惑的是,从有问题的代码片段
中删除using
var theImage = ApplicationGlobalWinForm.Properties.Resources.LanguageIcon;
PictureBox1.Image = theImage;
this.Icon = System.Drawing.Icon.FromHandle(theImage.GetHicon());
很好,谢谢。
我被难住了(我也没有解决内存扩展的问题),希望有一些WinForms专家可以解释一下。
谢谢!
我不是百分之百确定,但我认为是这样的
在第一个示例中,您将图像分配给PictureBox1.Image
,将this.Icon
设置为从theImage
创建的新图标(但不再引用theImage
),然后处置theImage
(留下using
块)。所以现在PictureBox1.Image
指的是一些被处理的东西,所以当油漆事件或类似的事情发生时,它会爆炸。
在第二个示例中,您从theImage
创建一个新图标(再次,不再引用theImage
),将this.Icon
设置为在上一步中创建的图标,然后将PictureBox1.Image
设置为从图标生成的新位图,最后处理theImage
,但由于没有人使用它,这无关紧要。我敢打赌,如果您调用PictureBox1.Image.Dispose()
,您将得到与第一个代码示例类似的结果。这也解释了为什么删除using语句会使一切恢复正常。