The Code Below allows you determine the Position of a Control, Relative to another Control. This is very useful for working with Control.Location & Drag/Drop behaviors.

#Region "XY Position Helpers"

    Public Enum ControlCorner
        TopLeft
        TopRight
        BottomLeft
        BottomRight
    End Enum

    Public Overloads Shared Function GetPositionOfCorner(ByVal argControl As Control, ByVal argCorner As ControlCorner, ByVal RelativeToParent As Control) As Drawing.Point
        Dim myTopLeftWidth As Integer = 0
        Dim myTopLeftHeight As Integer = 0

        Dim myControl As Control = argControl

        'Loop & Add Width/Height until we Find our RelativeToParent
        Do While myControl IsNot Nothing

            'Have we found the Parent?
            If myControl Is RelativeToParent Then
                Dim myCorner As Drawing.Point = GetPositionOfCornerRelativeToSelf(argControl, argCorner)
                Dim myPosition As New Drawing.Point(myTopLeftWidth + myCorner.X, myTopLeftHeight + myCorner.Y)
                Return myPosition
            End If

            'Add Width & Height
            myTopLeftWidth += myControl.Left
            myTopLeftHeight += myControl.Top

            'Next, Still searching for our Parent
            myControl = myControl.Parent
        Loop

        Throw New ArgumentException("Parent is not a Parent of Control!")
    End Function

    Public Overloads Shared Function GetPositionOfCornerRelativeToForm(ByVal argControl As Control, ByVal argCorner As ControlCorner) As Drawing.Point
        Return GetPositionOfCorner(argControl, argCorner, argControl.Form)
    End Function

    Public Shared Function GetPositionOfCornerRelativeToSelf(ByVal argControl As Control, ByVal argCorner As ControlCorner) As Drawing.Point
        Select Case argCorner
            Case ControlCorner.TopLeft
                Return New Drawing.Point(0, 0)
            Case ControlCorner.TopRight
                Return New Drawing.Point(argControl.Width, 0)
            Case ControlCorner.BottomLeft
                Return New Drawing.Point(0, argControl.Height)
            Case ControlCorner.BottomRight
                Return New Drawing.Point(argControl.Width, argControl.Height)
        End Select

        Throw New ArgumentException("Invalid Corner!")
    End Function

#End Region

Last edited Jul 11, 2009 at 12:36 AM by rdhatch, version 3

Comments

No comments yet.