MFC中onctlcolor函数返回的画刷导致的内存资源泄露问题

来源:互联网 发布:linux怎么删除组 编辑:程序博客网 时间:2024/05/18 22:41

onctlcolor函数内存泄露问题

然后需要补充几点,

如果你是通过GetWindowDC,或者GetDC,或者BeginPaint,取到必须释放。释放方法是ReleaseDC,这时不放你的程序不会崩溃,但是却会泄露,约来越大。

按钮上可以直接加载图片的,Bitmap图片,这本来很好,但是你一定只能LoadBitmap一次,再LoadBitmap一次就会漏了,这时怎么办啊,很简单。把 LoadBitmap存入局部变量HBITMAP啊,这样就没问题了,只是把指针放入其中。以后调用指针就可以,不用重复加载。

最后说一下OnCtlColor

网上有很多的解决方案,有的这样写:

HBRUSH       CTab4::OnCtlColor(CDC*       pDC,       CWnd*       pWnd,       UINT       nCtlColor)       
{   

if(m_hbr != NULL) {
        DeleteObject((HGDIOBJ)m_hbr);
        m_hbr = NULL;
    }

 HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
  pDC->SetTextColor(); 
  pDC->SetBkColor();
        m_hbr=(HBRUSH)GetStockObject(10);  //  
  m_hbr=CreateSolidBrush();  
         return m_hbr;


}   
网上无非就是把这个画刷定义为类成员,然后onctlcolor函数向上面这样写,但我试过了不行。正确的做法是下面msdn里说的,

在定义一个CBrush m_brush成员,并在构造函数里m_brush.createsolidbrush(RGB());这样初始化,注意是cbrush类型的,不是hbrush句柄createsolidbrush

MSDN里有例子如下:

// This OnCtlColor handler will change the color of a static control

// with the ID of IDC_MYSTATIC. The code assumes that the CMyDialog

//brush.createsolidbrush(RGB());

// class has an initialized and created CBrush member named m_brush.

// The control will be painted with red text and a background

// color of m_brush.

 

HBRUSH CZilchDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 

{

   // Call the base class implementation first! Otherwise, it may

   // undo what we're trying to accomplish here.

   HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

 

   // Are we painting the IDC_MYSTATIC control? We can use

   // CWnd::GetDlgCtrlID() to perform the most efficient test.

   if (pWnd->GetDlgCtrlID() == IDC_MYSTATIC)

   {

      // Set the text color to red

      pDC->SetTextColor(RGB(255, 0, 0));

 

      // Set the background mode for text to transparent 

      // so background will show thru.

      pDC->SetBkMode(TRANSPARENT);

 

      // Return handle to our CBrush object

      hbr = m_brush;

   }


   return hbr;

}

至此问题成功解决。

0 0
原创粉丝点击