如何检查颜色是否在特定位置?

时间:2015-05-15 16:37:19

标签: vb.net

我想知道,在VB 2010中,如何检查颜色是否在特定位置? 因此,例如,如果我的计时器正在滴答作响,我希望我的程序检查坐标507,208上的颜色是否为255,0,0。如果是,则程序将光标移动到那里并单击该位置然后停止计时器。现在我知道除了检查之外如何做到每一件事。如何检查该位置是否有颜色?我无法在谷歌上找到任何东西。 感谢名单!

2 个答案:

答案 0 :(得分:1)

如果要检查特定像素,可以这样做:

Private Function TakeScreenShot() As Bitmap
    Dim screenSize As Size = New Size(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
    Dim screenGrab As New Bitmap(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
    Using g As Graphics = Graphics.FromImage(screenGrab)
        g.CopyFromScreen(New Point(0, 0), New Point(0, 0), screenSize)
    End Using
    Return screenGrab
End Function

Dim MyBitMap as Bitmap = TakeScreenShot
If MyBitMap.GetPixel(507, 208) = Color.FromArgb(255,0,0) Then
.....

来自MyBitMap的地方取决于您在原始帖子中对我的问题的回答。

如果您正在扫描整个图像,您可能需要使用不同的方法,因为GetPixel可能相当慢。对调用ImageData返回的Image.LockBits进行迭代可能是最好的方法。

答案 1 :(得分:0)

使用Windows API的另一种方式(也是更快的方式):

<Runtime.InteropServices.DllImport("user32.dll")> _
Private Shared Function GetDC(hwnd As IntPtr) As IntPtr
End Function

<Runtime.InteropServices.DllImport("user32.dll")> _
Private Shared Function ReleaseDC(hwnd As IntPtr, hdc As IntPtr) As Int32
End Function

<Runtime.InteropServices.DllImport("gdi32.dll")> _
Private Shared Function GetPixel(hdc As IntPtr, nXPos As Integer, nYPos As Integer) As UInteger
End Function

Public Shared Function GetPixelColor(x As Integer, y As Integer) As System.Drawing.Color
    Dim hdc As IntPtr = GetDC(IntPtr.Zero)
    Dim pixel As UInteger = GetPixel(hdc, x, y)
    ReleaseDC(IntPtr.Zero, hdc)
    Dim c As Color = Color.FromArgb(CInt(pixel And &HFF), CInt(pixel And &HFF00) >> 8, CInt(pixel And &HFF0000) >> 16)
    Return c
End Function

用法:

Dim myColor As Color = GetPixelColor(100,300)