Q: How do I recognize a mouse click on a line?
A: Lines, once drawn, does not exist as a separate entity in Visual C++ applications, unlike CAD-like drawing applications. If you want to detect / select a line using mouse click, you will have to store the line details in the application and draw them on screen when it has to be displayed.
Easiest method to store a line is by storing its end points. I defined a convenient class CLine for this
where the end points are declared as data member of POINT pair. The constructor stores the parameters as its end points:
friend CDC& operator<<(CDC&, CLine&);
The function Dist returns the perpendicular distance from the point parameter to the line. The perpendicular distance is calculated using Analytical Geometry as
CLine::CLine(POINT start, POINT end)
Pt = start;
Pt = end;
Here, it is also calculated whether the foot of the perpendicular is within the bounds of the line also. If it is, actual value of perpendicular distance is returned. Otherwise, -1 is returned to indicate that the point is before the starting point or after the end point.
double CLine::Dist(POINT pt)
int DelX = Pt.x - Pt.x;
int DelY = Pt.y - Pt.y;
double D = sqrt(pow(DelX, 2) + pow(DelY, 2));
double Ratio = (double) ((pt.x - Pt.x) * DelX +
(pt.y - Pt.y) * DelY) / (DelX * DelX + DelY * DelY);
if (Ratio * (1 - Ratio) < 0)
return (double) abs(DelX * (pt.y - Pt.y) - DelY * (pt.x - Pt.x)) / D;
In the view, we can check whether the perpendicular distance from the mouse cursor point to the line is less than a pre-defined distance, in which case, you can say that the mouse is over the line. You can determine whether you are clicking on the line or not in your OnLButtonUp message handler function of WM_LBUTTONUP message.
void CClickLineView::OnLButtonUp(UINT nFlags, CPoint point)
// TODO: Add your message handler code here and/or call default
double D = pLine->Dist(point);
int Size = min(GetSystemMetrics(SM_CXCURSOR), GetSystemMetrics(SM_CYCURSOR));
if (D >= 0 && D < Size / 10)
// Mouse is over the line