Option Explicit
'定義壹個POINTAPI
Private Type POINTAPI
x As Long
y As Long
End Type
'定義壹個找色區域
Private Type RECT
Left As Long '區域坐標x
Top As Long '區域坐標y
Right As Long '區域寬
Bottom As Long '區域高
End Type
'Windows API 聲明
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long, ByVal x As Long, ByVal y As Long) As Long
'測試顏色函數,給定屏幕任意找色區域值,返回坐標位置
Private Function ifColor(x As RECT, ByVal color As Long) As POINTAPI
On Error Resume Next
Dim nTmpColor As Long, i As Long, j As Long
For i = x.Left To x.Left + x.Right
For j = x.Top To x.Top + x.Bottom
nTmpColor = GetPixel(GetDC(0), i, j)
If color = nTmpColor Then
ifColor.x = i
ifColor.y = j
Exit Function
End If
DoEvents
Next
Next
End Function
Private Sub Command1_Click() '全屏幕找色,時間花費較長
Dim t As POINTAPI, m As RECT
With m
.Top = 0
.Left = 0
.Bottom = Screen.Height / Screen.TwipsPerPixelY
.Right = Screen.Width / Screen.TwipsPerPixelX
End With
t = ifColor(m, 1447073)
Debug.Print t.x, t.y
End Sub
Private Sub Command2_Click() '某區域找色,時間花費少
Dim t As POINTAPI, m As RECT
With m
.Top = 300
.Left = 300
.Bottom = 100
.Right = 100
End With
t = ifColor(m, RGB(0, 125, 125))
Debug.Print t.x, t.y
End Sub