获取色彩

问题描述

我想在vb6中编写代码 当窗体放在屏幕上时。当单击按钮时,返回me.top和me.left位置的颜色。 我希望这是实时的(使用计时器)

我的代码

Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long,ByVal x As Long,ByVal y As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long

Private Sub Command1_Click()
Label3 = (GetPixel(GetDC(Me.hdc),Me.Left,Me.Top))
End Sub
Private Sub Timer1_Timer()
Label1.Caption = Me.Left
Label2.Caption = Me.Top

End Sub

代码无效,返回值-1

请帮助我

解决方法

使用VB6 - Screen shot function中的代码,您应该可以使用以下类似的方法从GetPixel获取有效值:

Dim Pixel As Long
Dim Left As Long
Dim Top As Long
Dim hDC As Long

' Get Desktop window
hDC = GetWindowDC(GetDesktopWindow)

' Use size of screen
Left = Me.Left \ Screen.TwipsPerPixelX
Top = Me.Top \ Screen.TwipsPerPixelY

Pixel = GetPixel(hDC,Left,Top)

这将为您提供一个COLORREF,您可以从中提取表单左上方的像素颜色。

您将需要在模块中声明以下功能:

Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long,ByVal X As Long,ByVal Y As Long) As Long
Declare Function GetDesktopWindow Lib "user32" () As Long
Declare Function GetWindowDC Lib "user32" (ByVal hWnd As Long) As Long

然后您可以使用以下功能从该像素提取RGB值:

Function GetRedValue(ByVal color As Long) As Long
    GetRedValue = color And &HFF&
End Function
 
Function GetGreenValue(ByVal color As Long) As Long
    GetGreenValue = (color \ &H100&) And &HFF&
End Function
 
Function GetBlueValue(ByVal color As Long) As Long
    GetBlueValue = (color \ &H10000) And &HFF&
End Function