Detecting clicks on a drawn line 

One of the most powerful "tricks of the trade" is being able to treat graphical shapes drawn on a Canvas as a control that can capture the mouse.  Detecting a mouse event is trivial for some shapes, like a sphere or square, and tedious for others.  Indeed highly complex shapes require numerical approximations.  One of the most common shapes that seems difficult to calculate a mouse hit for is the a line.  In fact, it is simple if you know the right formula.  The following code detects if a line (with endpoints P1 and P2) drawn on a PaintBox, is clicked. 

KEYWORDS: slope, abs

 

//---------------------------------------------------------------------------

void __fastcall TForm1::PaintBox1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) 

   int sens = 4; //sensitivity

    //test slope equality 
    if (abs((Y - P1.y)*(P2.x - X) - (x - P1.x)*(P2.y - Y)) < sens) 
    { 
        //make sure click is between enpoints 
        if ((X > P1.x && X < P2.x) || (X < P1.x && X >P2.x)) 
        { 
           //line has been clicked 
        } 
    }