I want to know if the mouse is over (hitting) a line. Therefore I created a
Region object that holds the line and use the IsVisible() method to test if
the mouse hits the line. It doesn't work! In the little program below I
create two Regions: one is square, the other is a line. Hit testing works on
the square-Region, not on the line-Region.
How can I do a hit-test over a line?
//namespace HitTest
namespace HitTest
{
//class Form
class Form:System.Win dows.Forms.Form
{
//two points that make up a line
System.Drawing. Point point1=new System.Drawing. Point(0,0);
System.Drawing. Point point2=new System.Drawing. Point(50,50);
//a rectangle
System.Drawing. Rectangle rectangle=new
System.Drawing. Rectangle(50,50 ,100,100);
//a line region
System.Drawing. Region line;
//a square region
System.Drawing. Region square;
//a brush
System.Drawing. Brush brush=System.Dr awing.Brushes.W hite;
//constructor
Form()
{
//set style for double buffered graphics
SetStyle
(
System.Windows. Forms.ControlSt yles.AllPaintin gInWmPaint|
System.Windows. Forms.ControlSt yles.DoubleBuff er|
System.Windows. Forms.ControlSt yles.ResizeRedr aw|
System.Windows. Forms.ControlSt yles.UserPaint,
true
);
//get a GraphicsPath object
System.Drawing. Drawing2D.Graph icsPath graphicspath=ne w
System.Drawing. Drawing2D.Graph icsPath();
//add a line to the graphicspath
graphicspath.Ad dLine(point1,po int2);
//use the graphicspath to define the line-region
line=new System.Drawing. Region(graphics path);
//use the rectangle to define the square-region
square=new System.Drawing. Region(rectangl e);
//prepare for mouse-input
MouseMove+=new System.Windows. Forms.MouseEven tHandler(OnMous eMove);
//prepare for paint
Paint+=new System.Windows. Forms.PaintEven tHandler(OnPain t);
}
//OnMouseMove
void OnMouseMove(obj ect a,System.Window s.Forms.MouseEv entArgs b)
{
//use White brush
brush=System.Dr awing.Brushes.W hite;
if(square.IsVis ible(b.X,b.Y))
{
//use Red brush if mouse is over square
brush=System.Dr awing.Brushes.R ed;
}
else if(line.IsVisib le(b.X,b.Y))
{
//use Blue brush if mouse is over line
brush=System.Dr awing.Brushes.B lue;
}
//force redraw
Invalidate();
}
//OnPaint
void OnPaint(object a,System.Window s.Forms.PaintEv entArgs b)
{
b.Graphics.Draw Line(System.Dra wing.Pens.Black ,point1,point2) ;
b.Graphics.Draw Rectangle(Syste m.Drawing.Pens. Black,rectangle );
b.Graphics.Fill Region(brush,sq uare);
}
//Main
public static void Main()
{
System.Windows. Forms.Applicati on.Run(new Form());
}
}
}