Memory problem when working with Desktop DC!


Please check the following program.
It's painting form's background to color of the pixel at current mouse coordinates.
Option Explicit

Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long

Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Sub Form_Load()

End Sub

Private Sub Timer1_Timer()
    Dim Color As Long
    Dim Dot As POINTAPI
    GetCursorPos Dot
    Color = GetPixel(GetWindowDC(GetDesktopWindow), Dot.x, Dot.y)
    'Color = GetPixel(GetWindowDC(0), Dot.x, Dot.y)
    Me.BackColor = Color
End Sub

The problem is that, when running, program is continuously consuming memory. (Task Manager -> Memory Usage)
I've discovered that every time I call  GetWindowDC(GetDesktopWindow), program consumes more memory.

I've considered capturing DesktopDC only once at Form_Load, but if I then press Ctrl+Alt+Del, the desktop DC changes so the old DC doesn't work any more.
So, even this way, I still have to capture desktop DC inside a timer to make sure it's not changed.

Why is this happening and how can I fix it?

I'm using Visual Basic 6.0 on Win2000 proffessional.

LVL 11
Who is Participating?
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try releasing your DC when you are done with it:

Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long

Private Sub Timer1_Timer()
    Dim Color As Long
    Dim Dot As POINTAPI
    Dim deskWnd As Long
    Dim deskDC As Long
    deskWnd = GetDesktopWindow()
    deskDC = GetWindowDC(deskWnd)
    GetCursorPos Dot
    Color = GetPixel(deskDC, Dot.x, Dot.y)
    ReleaseDC deskWnd, deskDC
    Me.BackColor = Color
End Sub
dbrckoviAuthor Commented:

It's working now.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.