Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDetermine whether a point lies inside a polygon in Visual Basic .NET
DescriptionThis example shows how to determine whether a point lies inside a polygonal path in Visual Basic .NET.
Keywordsgraphics, polygon, point, point in polygon, contains, polygon contains, polygon contains point, Visual Basic .NET, VB.NET
CategoriesGraphics
 

The GraphicsPath class provides an easy method for determining whether a point lies within a polygon. The following code wraps up a call to a GraphicsPath object's IsVisible method.

 
' Return true if the point is inside the polygon.
Private Function PointIsInPolygon(ByVal polygon() As Point, _
    ByVal target_point As Point) As Boolean
    ' Make a GraphicsPath containing the polygon.
    Dim path As New GraphicsPath()
    path.AddPolygon(polygon)

    ' See if the point is inside the path.
    Return path.IsVisible(target_point)
End Function
 
This code creates a GraphicsPath and adds the polygon to it. It then calls its IsVisible method to see whether the point lies within the polygon.

The program's MouseMove event handler uses PointIsInPolygon to change the form's cursor to a cross hair when the mouse is over the polygon.

 
' Set the cursor depending on whether the mouse is over the
' polygon.
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e _
    As System.Windows.Forms.MouseEventArgs) Handles _
    Me.MouseMove
    Dim new_cursor As Cursor
    If (PointIsInPolygon(Points, e.Location)) Then
        new_cursor = Cursors.Cross
    Else
        new_cursor = Cursors.Default
    End If

    ' Update the cursor.
    If (Me.Cursor <> new_cursor) Then Me.Cursor = new_cursor
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated