How to recognize a mouse click on a line?

I have a WPF application. There is a canvas. I draw a line when the user clicks on the canvas (from mouse to mouse). I take the starting point when the mouse is pressed and the ending point when the user makes the mouse. Then I calculate the distance and draw a line with a simple mouse click, movement and events.

After drawing many lines on the canvas, I click on any of the lines. I want to select a row and show the user which row is selected (for example, by changing the color of the line). Therefore, the user can delete it.

Thank.

0
source share
3 answers

Here's a working example: (implementing what Bala suggested in his comment)

private void myCanvas_Loaded(object sender, RoutedEventArgs e)
        {
            Line line = new Line();

            line.MouseDown += new MouseButtonEventHandler(line_MouseDown);
            line.MouseUp   += new MouseButtonEventHandler(line_MouseUp);

            line.Stroke = Brushes.Black;
            line.StrokeThickness = 2;
            line.X1 = 30; line.X2 = 80;
            line.Y1 = 30; line.Y2 = 30;

            myCanvas.Children.Add(line);
        }

void line_MouseUp(object sender, MouseButtonEventArgs e)
        {
            // Change line colour back to normal 
            ((Line)sender).Stroke = Brushes.Black;
        }

void line_MouseDown(object sender, MouseButtonEventArgs e)
        {
            // Change line Colour to something
            ((Line)sender).Stroke = Brushes.Red;
        }

, ,

( ) .

+4

MouseDown . , , , .

MouseDown :

:

  • = max (lineWidth, 10px),
  • , ( math.atan2),
  • Check if the new mouse coordinates are inside the rectangle,
  • If so, select your current lien and break.
0
source

All Articles