在Visual Basic中使用GetPixel/GetDC进行内存泄漏

Jer*_*ano 0 vb.net screen-scraping

我有一个计时器,除其他外,检查屏幕上的5个点是否有颜色变化.我的程序监控电话系统应用程序并检查是否有来自5个按钮中的任何一个的新来电.我根据我发布的另一个问题使用以下代码. 在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
Run Code Online (Sandbox Code Playgroud)

使用此代码,GDI对象可以非常快速地在短时间内突然出现,抛出OutOfMemory异常.我假设我没有正确释放DC,但我似乎无法找到任何其他方法来做到这一点.

Mic*_*Liu 5

调用GetDC(0)一次,将其保存到变量,并将变量传递给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
Run Code Online (Sandbox Code Playgroud)

注意,ReleaseDC有两个IntPtr参数,hWndhDC.