CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Mar 2009
    Posts
    29

    Does GetDC()->operator HDC() need a ReleaseDC?

    Hi all,

    I am calling a DLL function OnMouseMove which requires me to pass an HDC.

    I am using:
    Code:
    OnMouseMove{
    HDC hdc;
    hdc = GetDC()->operator HDC();
    
    DllFunc(hdc);
    ...
    }
    I don't see any memory leaks but the documentation suggest that when using GetDC(), a ReleaseDC() must follow.

    Is this accurate?
    Should i rewrite my function as below?

    Code:
    OnMouseMove{
    HDC hdc;
    CDC *pdc;
    
    pdc = GetDC();
    hdc = pdc->operator HDC();
    
    DllFunc(hdc);
    
    ReleaseDC(pdc);
    ...
    }
    Thanx in advance!

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    Re: Does GetDC()->operator HDC() need a ReleaseDC?

    GetDC without ReleaseDC may create resource leak, and not memory leak. The second code version is correct.

  3. #3
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Does GetDC()->operator HDC() need a ReleaseDC?

    ReleaseDC is only necessary for common DC's.
    If the window owns a DC (private or class dc) ReleaseDC is not necessary (although recommended).

    So yes, the 2nd version is prefered, although you can write it more compact.
    Code:
    CDC *pdc = GetDC();
    DllFunc(pdc->GetSafeHdc());
    ReleaseDC(pdc);

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Does GetDC()->operator HDC() need a ReleaseDC?

    And to avoid the problems with ReleaseDC - just don't use GetDC at all!
    There is the CClientDC class (MFC) which implicitly calls GetDC in its ctor and ReleaseDC in the dtor. So
    Code:
    CClientDC dc;
    hdc = dc.operator HDC();
    
    DllFunc(hdc);
    ...
    Victor Nijegorodov

  5. #5
    Join Date
    Mar 2009
    Posts
    29

    Re: Does GetDC()->operator HDC() need a ReleaseDC?

    Thanx guys!

    You have all been very helpful.

  6. #6
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: Does GetDC()->operator HDC() need a ReleaseDC?

    I also would suggest to call GetSafeHdc() (like in OReubens post) instead of operator HDC().
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured