Memory Leak using GetPixel/GetDC in Visual Basic

笑着哭i 提交于 2019-12-12 02:35:03

问题


I have a timer that among other things, checks 5 spots on the screen for a color change. My program monitors a phone system app and checks to see if there is a new incoming phone call from any of 5 buttons. I'm using the following code based on another question I had posted. Monitor an area of the screen for a certain color in Visual Basic

Private Function CheckforCall()
    Try
        Dim queue1 As Integer = GetPixel(GetDC(0), 40, 573)
        Dim queue2 As Integer = GetPixel(GetDC(0), 140, 573)
        Dim queue3 As Integer = GetPixel(GetDC(0), 240, 573)
        Dim queue4 As Integer = GetPixel(GetDC(0), 340, 573)
        Dim queue5 As Integer = GetPixel(GetDC(0), 440, 573)
        ReleaseDC(0)

    <code snipped - Checks to see if the pixel color matches and 
       returns true or false>

    Catch ex As Exception
        Return False
    End Try
End Function

Using this code, GDI Objects skyrockets very quickly and within short order, throws an OutOfMemory exception. I'm assuming I'm not releasing the DC properly, but I can't seem to find any other way to do it.


回答1:


Call GetDC(0) once, save it to a variable, and pass the variable to ReleaseDC:

Dim hDC As IntPtr = GetDC(0)
Try
    Dim queue1 As Integer = GetPixel(hDC, 40, 573)
    Dim queue2 As Integer = GetPixel(hDC, 140, 573)
    Dim queue3 As Integer = GetPixel(hDC, 240, 573)
    Dim queue4 As Integer = GetPixel(hDC, 340, 573)
    Dim queue5 As Integer = GetPixel(hDC, 440, 573)
    ...
Catch ex As Exception
    Return False
Finally
    ReleaseDC(0, hDC)
End Try

Note that ReleaseDC takes two IntPtr arguments, hWnd and hDC.



来源:https://stackoverflow.com/questions/10048733/memory-leak-using-getpixel-getdc-in-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!