本文介绍了如何真正配置内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在屏幕上创建了许多表单,并为每个表单分配了大小调整事件.
resize事件将在位图上绘制一个矩形,然后获取
此位图中的一个IntPtr hBM,将此hBM分配给form_input
backgroupimage如下.

I create many forms on Screen, and assign resize event to each form.
the resize event will draw a rectangle to a bitmap, and then get
an IntPtr hBM from this bitmap, assign this hBM to form_input
backgroupimage as follow.

void form_Resize(object sender, EventArgs e)
{
  Form Form_Input = (Form)sender;
  Rectangle Rec = Form_Input.ClientRectangle;
  Bitmap bm = new Bitmap(Rec.Width, Rec.Height);
  Graphics G = Graphics.FromImage(bm);
  Brush B = new SolidBrush(Form_Input.BackColor);
  G.FillRectangle(B, Rec);
  IntPtr hBM = bm.GetHbitmap();
  Form_Input.BackgroundImage = Image.FromHbitmap(hBM);
  G.Dispose();
  bm.Dispose();
}



当我多次调整窗体的大小时,它将弹出错误消息
的"OutOfMemoryException".

为什么会发生?! G.Dispose()和bm.Dispose()的行不能工作
真正配置内存好吗?我该如何解决这个问题?谢谢.



when I resize one of the Form many times, it then will pop up error message
of ''OutOfMemoryException''.

Why it happens ?! does the line of G.Dispose() and bm.Dispose() can not work
well to really dispose memory ? How can I solve the problem ? Thanks.

推荐答案

using (Bitmap bm = new Bitmap(Rec.Width, Rec.Height)) {
    using (Brush B = new SolidBrush(Form_Input.BackColor)) {
        using (Graphics G = Graphics.FromImage(bm)) {
            //use bm, B, G here...
        } // G.Dispose is called automatically
    } // B.Dispose is called automatically
} // bm.Dispose is called automatically


请参阅 http://msdn.microsoft.com/en-us/library/yh598w02.aspx [ ^ ].

—SA


See http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].

—SA




这篇关于如何真正配置内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 14:02