2012-04-06 23 views
0

我有一個計時器,其中包括在屏幕上檢查5個色點的顏色變化。我的程序會監控電話系統應用程序,並檢查是否有來自5個按鈕中任何一個的新來電。基於我發佈的另一個問題,我正在使用以下代碼。 Monitor an area of the screen for a certain color in Visual Basic在Visual Basic中使用GetPixel/GetDC的內存泄漏

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 

使用此代碼,GDI對象一飛沖天非常迅速,短期內內,拋出OutOfMemory例外。我假設我沒有正確地發佈DC,但我似乎無法找到任何其他方式來做到這一點。

回答

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 

注意ReleaseDC需要兩個IntPtr參數,hWndhDC

+1

另外,將ReleaseDC放在finally塊中,所以即使在異常情況下也可以清理它。 – 2012-04-06 21:08:41

+0

最後,不是抓住。現在它不會在正常路徑上清理。 :-) – 2012-04-06 21:27:12

+0

@JasonMalinowski:哎呀!我現在知道了嗎? – 2012-04-06 21:28:32