Perform Hit Testing with Shapes

Problem

You want to detect if a user clicks inside a shape.

Solution

Test the point where the user clicked with the Rectangle.Contains or GraphicsPath.IsVisible method.

Discussion

If you are creating a program that has custom graphical elements the user can interact with, you need to be able to determine when the user’s mouse is inside or outside a given shape. The .NET Framework provides two methods that can help with this task. The first is the Rectangle.Contains method, which takes a point and returns True if the point is inside the rectangle.

For example, you might add the following code to the drawing program demonstrated in recipe Paint Dynamic Content to check if the point where the user right-clicked lies inside ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.