How to: Use Hit Testing with a Region

The purpose of hit testing is to determine whether the cursor is over a given object, such as an icon or a button.


The following example creates a plus-shaped region by forming the union of two rectangular regions. Assume that the variable point holds the location of the most recent click. The code checks to see whether point is in the plus-shaped region. If the point is in the region (a hit), the region is filled with an opaque red brush. Otherwise, the region is filled with a semitransparent red brush.

Point point = new Point(60, 10);

// Assume that the variable "point" contains the location of the
// most recent mouse click.
// To simulate a hit, assign (60, 10) to point.
// To simulate a miss, assign (0, 0) to point.

SolidBrush solidBrush = new SolidBrush(Color.Black);
Region region1 = new Region(new Rectangle(50, 0, 50, 150));
Region region2 = new Region(new Rectangle(0, 50, 150, 50));

// Create a plus-shaped region by forming the union of region1 and 
// region2.
// The union replaces region1.

if (region1.IsVisible(point, e.Graphics))
    // The point is in the region. Use an opaque brush.
    solidBrush.Color = Color.FromArgb(255, 255, 0, 0);
    // The point is not in the region. Use a semitransparent brush.
    solidBrush.Color = Color.FromArgb(64, 255, 0, 0);

e.Graphics.FillRegion(solidBrush, region1);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of PaintEventHandler.

See Also