Wince GDI资源泄露可能原因

Wince GDI资源泄露可能原因

在网上找了很多人的博客来看,在各种论坛里面看高手的回复,把Wince GDI资源泄露的可能原因总结了一下
(1)不要用CDC做直接用HDC
(2)OnEraseBkgnd擦除背景函数没用,只有一句return true;,所以把Invalidate();改成Invalidate(0);
(3)    BUG: Memory leaks when you use the CWnd class versions of the GetDC method and the ReleaseDC method
    When you run code that calls the CWnd::GetDC function followed by the CWnd::ReleaseDC function, a memory leak of 4 bytes occurs. The cause of this bug is currently unknown. To avoid this problem, do not use the CWnd class versions of the GetDC method and the ReleaseDC method. Use the GetDC function and the ReleaseDC function. Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.
    Steps to Reproduce the Behavior
In a method that is a part of a class that is derived from CWnd, insert the following code in your application:
[cpp]  view plain copy
  1. CDC *pDC;  
  2. RECT rect;  
  3.   
  4. GetClientRect (&rect);  
  5.   
  6. for (int i = 0; i < 1000; i++)  
  7. {  
  8.     pDC = GetDC ();  
  9.     ReleaseDC (pDC);  
  10. }  

    If you run this code and then check the system memory before and after you run the code, you notice that the system memory leaks four bytes per iteration. If you change the code to the following code, the memory leak does not occur:
 HDC hDC;
[cpp]  view plain copy
  1. RECT rect;  
  2. ::GetClientRect (m_hWnd, &rect);  
  3.   
  4. for (int i = 0; i < 1000; i++)  
  5. {  
  6.     hDC = ::GetDC (m_hWnd);  
  7.     ::DrawText (hDC, L"Testing...", 10, &rect, DT_CENTER);  
  8.     ::ReleaseDC (m_hWnd, hDC);  
  9. }  
(4) 如果过于频繁的使用CreateCompatibleDC这种的话可以改为成员变量,在析构函数中释放。
(5) 创建的Gdiobj如果执行了selectobject,一般要这样删除,例如pOldFont=selectobject(&m_fontSongTi);在删除时要先pDC->SelectObject(pOldFont);再删除GDI资源,m_fontSongTi.deleteobject(); 

附:GDI使用的几个注意点:

1、Create出来的GDI对象,要用Deleteobject释放, create出来的DC,要用DeleteDc释放,getDC得出的DC,用ReleaseDc释放。

2、先create后delete, create1,create2, delete2,delete1的顺序。

3、画图步骤

a 创建一个内存兼容dc(CreateCompatibleDC)
b.创建一个内存兼容bitmap(CreateCompatibleBitmap)
c.关联创建的内存兼容dc和bitmap(SelectObject)
d.画图
e.BitBlt到目的dc上
f.断开内存兼容dc和bitmap关联(SelectObject)
g.销毁内存兼容bitmap
h.销毁内存兼容dc


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值