Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a small matter of GDI leak and i wanted to know someone's opinion on how to solve this.Say i have a class that enfolds data specific to creating and handling a window ex:
class Wnd  {
   HWND hWnd;
   HFONT hFont;
   LOGFONT LogFont;
   //etc
public:
   //constructors and member functions
   //The following function atempts to change the font of the window
   //pointed to by the hWnd parameter
   void ChangeFont (const LOGFONT& lf)  {
      std::memcpy (&LogFont,&lf,sizeof(LOGFONT));
      hFont=CreateFontIndirect (&LogFont);
      SendMessage (hWnd,WM_SETFONT,(WPARAM) hFont,(LPARAM) 1);
    }
   ~Wnd ()  {
      //i don't think this would work since i haven't used the SelectObject function
      DeleteObject ((HGDIOBJ) hFont);
    }
 };

So the main question is , at destruction time how do i release the memory allocated to the hFont parameter?Should i get a device context of the window and use the SelectObject () function so that after that i could release it calling the function for the old font and use DeleteObject () to free the memory?Thanks a lot.
Posted

The hFont memory is owned by the system and will be freed when you call DeleteObject() (or DeleteFont()). Why do you need to make a copy of the LOGFONT structure in order to create the hFont object, just use the original.
 
Share this answer
 
I inherit from it and i need a member LOGFONT variable.So can i delete it in the body of the destructor ?Because i tried and the actual cleanup isn't performed properly.And thanks for the answer.
 
Share this answer
 
class Wnd
{
  HWND     hWnd;
  HFONT    hFont;
  LOGFONT  LogFont;
    //etc
public:
    //constructors and member functions
    //The following function atempts to change the font of the window
    //pointed to by the hWnd parameter
  void ChangeFont(const LOGFONT& lf)
  {
    memcpy(&LogFont,&lf,sizeof(LOGFONT));
    if(hFont) DeleteObject(hFont);
    hFont = CreateFontIndirect (&LogFont);
    SendMessage(hWnd,WM_SETFONT,(WPARAM)(hFont?hFont:GetStockObject(ANSI_VAR_FONT),(LPARAM)1);
  }
  Wnd()
  {
    hWnd  = 0;
    hFont = 0;
    // ...
  }
  ~Wnd()
  {
    //i don't think this would work since i haven't used the SelectObject function
    if(hFont) DeleteObject(hFont);
  }
};

That looks better, Regards.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900