Attribute VB_Name = "Module1"
Sub ColorToRGB(ByVal lColorCode As Long, ByRef iRed As Integer, ByRef iGreen As Integer, ByRef iBlue As Integer)

    Dim lColor As Long
    lColor = lColorCode      'work long
    iRed = lColor Mod &H100  'get red component
    lColor = lColor \ &H100  'divide
    iGreen = lColor Mod &H100 'get green component
    lColor = lColor \ &H100  'divide
    iBlue = lColor Mod &H100 'get blue component

End Sub
Function AvePicDifference(ByRef Pic1 As PictureBox, ByRef Pic2 As PictureBox, ByVal X1, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long, ByVal W As Long, ByVal H As Long) As Double
    Dim TPX As Long
    Dim TPY As Long
    Dim col1 As Long
    Dim col2 As Long
    Dim r1 As Integer
    Dim g1 As Integer
    Dim b1 As Integer
    Dim r2 As Integer
    Dim g2 As Integer
    Dim b2 As Integer
    Dim Dist As Double
    Dim Cnt As Double
    TPX = Screen.TwipsPerPixelX
    TPY = Screen.TwipsPerPixelY
    Dist = 0
    Cnt = 0
    For Y = 0 To H - 1 Step TPY
        For X = 0 To W - 1 Step TPX
            
            col1 = Pic1.Point(X + X1, Y + Y1)
            col2 = Pic2.Point(X + X2, Y + Y2)
        
            ColorToRGB col1, r1, g1, b1
            ColorToRGB col2, r2, g2, b2
            
            Dist = Dist + Sqr(((r1 - r2) ^ 2) + ((g1 - g2) ^ 2) + ((b1 - b2) ^ 2))
            Cnt = Cnt + 1
        
        Next X
    Next Y
    AvePicDifference = ((Dist / Cnt) / 442) * 100
End Function

Function ScanDeltaX(ByRef Pic1 As PictureBox, ByRef Pic2 As PictureBox, ByVal npX1 As Long, ByVal npY1 As Long, ByVal W As Long, ByVal H As Long, ByVal XBuffer As Long, ByVal YBuffer As Long) As Long
    Dim X1 As Long
    Dim Y1 As Long
    
    Dim TPX As Long
    Dim TPY As Long
    
    TPX = Screen.TwipsPerPixelX
    TPY = Screen.TwipsPerPixelY
    
    X1 = npX1
    Y1 = npY1
   
    Dim MinDiff As Double
    Dim MinX As Long
    MinDiff = 3 * TPY
    MinX = 0
    
    Dim Ret As Double
    For Y = -YBuffer To YBuffer Step TPY
        For X = (X1 - XBuffer) To (X1 + XBuffer) Step TPX
    
            'If Abs(X - X1) <= MaxDelta Then
                Ret = AvePicDifference(Pic1, Pic2, X1, Y1, X, (Y1 + Y), W, H)
                
                If Ret < MinDiff Then
                    MinDiff = Ret
                    MinX = X
                End If
            'End If
                
        Next X
    Next Y
    
    ScanDeltaX = MinX - X1
    
End Function



