-
DeleteObject
Question about deleteobject.
I have the following code for changing font to bold in a control.
Code:
void CtrlWindow::FontBold(bool showBold)
{
LOGFONT newLFont;
LOGFONT oldLFont;
HFONT newFont;
HFONT oldFont;
oldFont=(HFONT)SendMessage(m_hwnd,WM_GETFONT,0,0);
//GetTextMetrics(GetDC(m_hwnd),&textM);
GetObject(oldFont,sizeof(LOGFONT),&oldLFont);
newLFont.lfCharSet=oldLFont.lfCharSet;
newLFont.lfClipPrecision=oldLFont.lfClipPrecision;
newLFont.lfEscapement=oldLFont.lfEscapement;
ZeroMemory((void*)newLFont.lfFaceName,32);
CopyMemory((void*)newLFont.lfFaceName,oldLFont.lfFaceName,32);
newLFont.lfHeight=oldLFont.lfHeight;
newLFont.lfItalic=oldLFont.lfItalic;
newLFont.lfOrientation=oldLFont.lfOrientation;
newLFont.lfOutPrecision=oldLFont.lfOutPrecision;
newLFont.lfPitchAndFamily=oldLFont.lfPitchAndFamily;
newLFont.lfQuality=oldLFont.lfQuality;
newLFont.lfStrikeOut=oldLFont.lfStrikeOut;
newLFont.lfUnderline=oldLFont.lfUnderline;
if (showBold==true)
{
newLFont.lfWeight=700;
}
else
{
newLFont.lfWeight=400;
}
newLFont.lfWidth=oldLFont.lfWidth;
newFont=CreateFontIndirect(&newLFont);
SendMessage(m_hwnd,WM_SETFONT, (WPARAM)newFont, MAKELPARAM(TRUE,0)) ;
//DeleteObject(newFont);
}
If I dont delete the object I get memory leaks.
If I do delete the object the bold text gets garbled. on second call the text is completly removed.
Am I going about this the wrong way?
Is it because the sendmessage doesnt have the time to set the font before it is deleted?
Thanks
Packetvb
-
Re: DeleteObject
It's because you delete the font that the control is trying to use. It doesn't make a copy.
Create all fonts you need in the object constructor, delete them in the object destructor. In-between you just set them.
-
Re: DeleteObject
Thanks CornedBee.
Im trying to have method in class for changing font in a control to any fontname.
Since it is the call to createfontindirect that requires the delete, would there be any problems changing the members of the oldFont variable and Sending a message to the control with that font. Wouldnt that remove the need to delete the font object?
Packetvb
-
Re: DeleteObject
No, it wouldn't.
OK, so store the one font you have. When switching font, create a new one and store it in a local temporary. Assign it to the control. Thus the font doesn't use the old one anymore, which you can now delete:
[code]class Ctrl
HFONT font;
void switch(string fontname)
{
HFONT newfont = createfont(fontname);
setcontrolfont(thecontrol, newfont);
deleteobject(font);
font = newfont;
}
};
-
Re: DeleteObject
Yea, Actually the last question I asked was a bit stupid.
I got it working by doing something similiar to what you suggest.
After I send a Message to the control with the newFont, I deleteobject on the oldFont. Seems to have taken care of mem leak.
Thanks CornedBee
Packetvb/SpeedBasic