1

I need to implement hit-testing for my Windows Form Control. I have my custom class which inherits the Control class and I draw, in the OnPaint method, a polyline:

e.Graphics.DrawLines(myPen, myPoints);

Now, during the MouseDown event I get the position of the mouse and I implement the hit-testing like follow:

using (var path = new GraphicsPath())
{  
   path.AddLines(myPoints);
   return path.IsVisible(pt);
}

The problem is that if have, for example, the polyline in figure (which may seem like a polygon) the IsVisible method returns true even if I click inside the region that represents this polygon:

enter image description here

I need a different behavior, the method have to return true only if I click over the line. How can I do?

Nick
  • 10,309
  • 21
  • 97
  • 201
  • 1
    A better solution would be to create an object / a *model* that represents the form you want, that draws itself. Then the object will be responsible for the check if it is hit (in what area) and not the main program. In the main application you just pass the mouse coordinates for every object you want to check. – keenthinker May 03 '14 at 10:47
  • 1
    @pasty thanks for your advice, actually I'm doing just as you say. The question is just a simpler example. – Nick May 03 '14 at 10:56
  • @Nick as I posted in [answer](http://stackoverflow.com/a/23443391/1207195), you just need to replace `IsVisible` with `IsOutlineVisible`. – Adriano Repetti May 03 '14 at 11:07

1 Answers1

4

You just need to use a different method for hit-testing: IsOutlineVisible instead of IsVisible.

using (var path = new GraphicsPath())
{  
   path.AddLines(myPoints);
   return path.IsOutlineVisible(pt, Pens.Black);
}

You need to provide a pen because line-based hit-testing works with line and lines can have a specific width. That said I'd suggest to use a different (thicker) pen from what you use for drawing because to pick a single pixel with mouse isn't such easy for many many users.

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208