GetPixel Memory Leak

mikecarter

New member
Joined
Apr 16, 2008
Messages
4
Programming Experience
3-5
Hi all!

I'm hoping someone can help me here. This SHOULD be basic but it is bugging me. :confused:

I have some code (below), very simple, which just changes a label's background to the color of the pixel under the mouse pointer.

The problem is, each time the color changes the memory (in task manager) for my program gets larger, eventually resulting in an Out of Memory exception.

All I have on the form is a timer with an interval of 100 and a label.

Here is the code (VB.NET 2008):
VB.NET:
Option Strict On

Public Class Form1
    Public Declare Function GetPixel Lib "gdi32.dll" (ByVal hdc As IntPtr, ByVal nXPos As Int32, ByVal nYPos As Int32) As Int32
    Private Declare Function GetDC Lib "user32.dll" (ByVal hWnd As IntPtr) As IntPtr
    Private Declare Function ReleaseDC Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal hdc As IntPtr) As Int32

    Private m_hdc As IntPtr

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        Me.Timer1.Enabled = True
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        m_hdc = GetDC(IntPtr.Zero)

        Me.Label1.BackColor = ColorTranslator.FromWin32(GetPixel(m_hdc, Cursor.Position.X, Cursor.Position.Y))

        ReleaseDC(IntPtr.Zero, m_hdc)
    End Sub
End Class


Any ideas?

Thanks,
Mike
 
Or Maybe.

Notes:
For .NET 2.0, consider using Microsoft.Win32.SafeHandles.SafeFileHandle instead. It can be used where IntPtr is used.
 
This seems to have slown down the leak but not stopped it completely.

It hasn't crashed by program since I have done both of the above steps, so hopefully it's a case of close enough is good enough.


Thanks, :D
Mike
 
Are you closing the pixel handle? Try not passing the pixel directly to ColorTranslator.FromWin32.

ie.

pixel = GetPixel(m_hdc, Cursor.Position.X, Cursor.Position.Y)
Me.Label1.BackColor = ColorTranslator.FromWin32(pixel)

CloseHandle(pixel)
 
Back
Top