amin
amin

Reputation: 1

Detection Color from screen of exe file

I have a printer control program( EXE file)

When the printer is working properly, the program shows green color. And displays red color when stopped. Now: I want to write a color recognition code in Visual Basic In such a way that the written program be can detect the color change of that Exe program. That is, to understand when the printer is a stop and when it starts

The code I wrote has a problem : when I put the form on the paint. The color codes care different And I can not do this check with multiple codes

my code:

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




Private Sub Timer1_Timer()
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)

Me.Caption = Hex(Pixel)
Me.BackColor = Pixel
End Sub

image1

1

image2

2

Upvotes: 0

Views: 304

Answers (1)

Étienne Laneville
Étienne Laneville

Reputation: 5021

It looks like the Pixel data is taken from the title bar of your window. The red in your image is closer to 236 (236,26,37 is the RGB value) and what your form is showing converts to 137,126,180 (RGB for 897EB4) and 146,135,187 (RGB for 9287BB). You can see that the color is wrong because the background of your form doesn't match the red from the desktop.

I would try reading the Pixel further away from the form:

Left = (Me.Left / Screen.TwipsPerPixelX) - 20
Top = (Me.Top / Screen.TwipsPerPixelY) - 20

Nonetheless, even if the color is affected by the dropshadow, you can implement some tolerance for the value you are receiving. For example, you should accept values within +/- 10 of your expected value using a function like this:

Function CheckColor(p_iRed, p_iGreen, p_iBlue, p_iTargetRed, p_iTargetGreen, p_iTargetBlue, p_iTolerance) As Boolean
    CheckColor = CheckColorPart(p_iRed, p_iTargetRed, p_iTolerance) And CheckColorPart(p_iGreen, p_iTargetGreen, p_iTolerance) And CheckColorPart(p_iBlue, p_iTargetBlue, p_iTolerance)
End Function

Function CheckColorPart(p_iValue, p_iTarget, p_iTolerance) As Boolean
    CheckColorPart = (p_iValue >= p_iTarget - p_iTolerance And p_iValue <= p_iTarget + p_iTolerance)
End Function

This should handle the slight variations in color you are seeing and detect what you are looking for.

Upvotes: 1

Related Questions