怀疑是GDI内存泄漏。程序运行两到三天就提示系统内存严重不足。请帮忙看一下哪里有问题,谢谢!
为了避免界面刷新闪烁,重写了OnEraseBkgnd函数。
//OnEraseBkgnd
BOOL CdamonDlg::OnEraseBkgnd(CDC *pDC)
{
if (!bCreate)// CDC hDCMem。防止频繁申请释放造成内存碎片,所以只创建一次
{
bCreate = TRUE;
hDCMem.CreateCompatibleDC(NULL); //创建虚拟DC
::GetClientRect(this->m_hWnd,&rc); //得到窗口矩形
hBm=CreateCompatibleBitmap(*pDC,rc.right-rc.left,rc.bottom -rc.top);//将窗口矩形存入位图
}
SelectObject(hDCMem,hBm);
hDCMem.FillSolidRect(&rc,BACKCOL);
DrawInfo1(&hDCMem,this,_T(""));//顶部状态栏绘制
DrawTextSelf1(&hDCMem,_T("警报发放"),CRect(45,307,130,330),25,1000,FONTCOL);
DrawTextSelf1(&hDCMem,_T("语音广播"),CRect(170,307,255,330),25,1000,FONTCOL);
DrawTextSelf1(&hDCMem,_T("短信收发"),CRect(295,307,380,330),25,1000,FONTCOL);
DrawTextSelf1(&hDCMem,_T("设备状态"),CRect(420,307,505,330),25,1000,FONTCOL);
DrawTextSelf1(&hDCMem,_T("系统设置"),CRect(545,307,630,330),25,1000,FONTCOL);
DrawTextSelf1(&hDCMem,_T("用户登录"),CRect(670,307,755,330),25,1000,FONTCOL);
DrawTextSelf1_L(&hDCMem,_T("浙江圆融科技有限公司"),CRect(550,380,780,410),25,1000,WHITECOL,DT_RIGHT);
DrawTextSelf1_L(&hDCMem,_T("浙江省人民防空办公室"),CRect(550,410,780,440),25,1000,WHITECOL,DT_RIGHT);
DrawTextSelf1_L(&hDCMem,_T("中国人民解放军理工大学"),CRect(470,440,780,470),25,1000,WHITECOL,DT_RIGHT);
pDC->BitBlt(0,0,rc.right-rc.left,rc.bottom-rc.top,&hDCMem,0,0,SRCCOPY);
return TRUE;
}
//DrawTextSelf1
void DrawTextSelf1(CDC* mdc,CString Text,CRect &Rect,int lfHeight,int lfWeight,COLORREF lfColor,DWORD dwStyle)
{
CFont font;
LOGFONT lf;
memset(&lf, 0, sizeof(LOGFONT));
lf.lfHeight = lfHeight;
lf.lfWeight = lfWeight;
lstrcpy(lf.lfFaceName,_T("微软雅黑"));
lf.lfQuality = CLEARTYPE_QUALITY;
//lf.lfCharSet = GB2312_CHARSET;
font.CreateFontIndirect(&lf);
CFont* pOldFont = mdc->SelectObject(&font);
mdc->SetBkMode(TRANSPARENT);
mdc->SetTextColor(lfColor);
mdc->DrawText(Text,-1,Rect,(dwStyle==DT_CENTER | DT_WORDBREAK)?dwStyle:(dwStyle | DT_WORDBREAK));
mdc->SelectObject(pOldFont);
if (!DeleteObject(font))
{
RETAILMSG(LFT_DEBUG_MSG_OUT,(_T("delete font failed!\n")));
}
}
//DrawTextSelf1_L。其实这个函数和上一个函数基本一样,是可以替换掉的,暂时没有做这个工作
void DrawTextSelf1_L(CDC* mdc,CString Text,CRect &Rect,int lfHeight,int lfWeight,COLORREF lfColor,DWORD dwStyle)
{
CFont font;
LOGFONT lf;
memset(&lf, 0, sizeof(LOGFONT));
lf.lfHeight = lfHeight;
lf.lfWeight = lfWeight;
lstrcpy(lf.lfFaceName,_T("微软雅黑"));
lf.lfQuality = CLEARTYPE_QUALITY;
//lf.lfCharSet = GB2312_CHARSET;
font.CreateFontIndirect(&lf);
CFont* pOldFont = mdc->SelectObject(&font);
//mdc->SelectObject(&font);
//mdc->SelectObject(&font);
mdc->SetBkMode(TRANSPARENT);
mdc->SetTextColor(lfColor);
mdc->DrawText(Text,-1,Rect,(dwStyle==DT_LEFT | DT_WORDBREAK)?dwStyle:(dwStyle | DT_WORDBREAK));
mdc->SelectObject(pOldFont);
if (!DeleteObject(font))
{
RETAILMSG(LFT_DEBUG_MSG_OUT,(_T("delete font failed!\n")));
}
}
------解决思路----------------------
怀疑是 GDI,就可以试试先将与 GDI 相关的功能注释掉进行测试,看看是否还有内存泄露?
同时,将与 GDI 相关的代码,分成几个模块进行单独的内存泄露测试,确定内存泄露可能出现的范围。现在从代码上,没有明显的 GDI 泄露问题。
但其它相关 GDI 的代码呢,如:DrawInfo1()。