• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 336
  • Last Modified:

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.

1 Solution
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.


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now