在拍摄内存扩展问题时,我遇到了一个让我感到困惑的异常现象。
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是一个工作区映像。using是我寻找内存扩展问题的一部分。在保存上述代码的方法完成后,应用程序会遇到“System.ArgumentException类型的未处理异常发生在System.Drawing.dll中”。
将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专家可以解释这些事情。
谢谢!
发布于 2015-07-28 22:57:50
我不是百分之百确定,但我认为正在发生的事情如下。
在第一个示例中,您将theImage分配给PictureBox1.Image,将this.Icon设置为从theImage创建的新图标(但不再引用theImage),然后处理theImage (离开using块)。所以现在PictureBox1.Image指的是被处理的东西,所以当一个油漆事件或者类似的事情发生时,它就会爆炸。
在第二个示例中,您从theImage (再次,不再引用theImage)创建一个新的图标,将this.Icon设置为在上一步中创建的图标,然后将PictureBox1.Image设置为从该图标生成的新位图,最后您将处理theImage,但由于不再使用theImage,所以这并不重要。我敢打赌,如果您调用PictureBox1.Image.Dispose(),您将得到与第一个代码示例中类似的结果。这也解释了为什么删除using语句会使一切再次正常工作。
https://stackoverflow.com/questions/31688243
复制相似问题