title: Calculate the closest Point on a Line to another Point
body: <p>I'm trying to put a Point on a Path in WPF. In the Xaml everything is working fine. I have a path and when i click on it (or near it) my Create Point Handler gets fired. It will create a Point for me, but this Point wont sit exactly on my path.</p>
  
  <p>I tried to do some calculations to get the exact coordinates for my Point, but it got even worse, now my points are as close as before or sometimes the distance to my path gets even bigger. I cannot figure out why. Heres my event handler, please help me. (The first calculation regarding <code>deviation</code> is for me to figure out at which index in my List i have to insert the new Point. This is working fine.)</p>
  
  <pre><code>private void CreatePointHandler(MouseEventArgs e)
      {
          Path clickedPath = e.OriginalSource as Path;
          FrameworkElement parentCanvas = clickedPath.Parent as FrameworkElement;
          Point pos = e.GetPosition(parentCanvas);
          ConnectionPoint p = new ConnectionPoint(RaisePointsChanged);            
  
          for (int i = 0; i &lt; Points.Count - 1; i++) {
              double d1 = (Math.Abs(Points[i].X - Points[i + 1].X)) * (Math.Abs(pos.Y - Points[i + 1].Y));
              double d2 = (Math.Abs(Points[i].Y - Points[i + 1].Y)) * (Math.Abs(pos.X - Points[i + 1].X));
              double deviation = Math.Abs(d1 - d2);
              if (deviation &lt; 3000 &amp;&amp; ((Points[i].X &lt; pos.X &amp;&amp; pos.X &lt; Points[i+1].X) || (Points[i].X &gt; pos.X &amp;&amp; pos.X &gt; Points[i+1].X))
                                   &amp;&amp; ((Points[i].Y &lt; pos.Y &amp;&amp; pos.Y &lt; Points[i+1].Y) || (Points[i].Y &gt; pos.Y &amp;&amp; pos.Y &gt; Points[i+1].Y))) {
  
                  Vector iToIPlus1 = new Vector(Points[i + 1].X - Points[i].X, Points[i + 1].Y - Points[i].Y);
                  Vector iToPos = new Vector(pos.X - Points[i].X, pos.Y - Points[i].Y);
  
  
                  double t = (iToPos.X * iToIPlus1.X + iToPos.Y * iToIPlus1.Y) / (iToIPlus1.X * iToIPlus1.X + iToIPlus1 * iToIPlus1);
  
                  p.X = Points[i].X + t * iToIPlus1.X;
                  p.Y = Points[i].Y + t * iToIPlus1.Y;
  
                  Points.Insert(i + 1, p);
                  return;
              }
          }                       
      }
  </code></pre>