The task is to draw a line on the selection of the corresponding button on the toolbar.
In my code, I try to implement the following algorithm : click LMB on the workspace, move the cursor to another place, hold LMB pressed, release LMB - draw a line according to the coordinates of the place where the button was pressed and where it was released.

I declare global variables:

Point EndPosition; Point StartPosition; 


Code:

 private void inkCanvas1_MouseDown(object sender, MouseButtonEventArgs e) { FrameworkElement fe = sender as FrameworkElement; StartPosition = e.MouseDevice.GetPosition(fe); } private void Line_Click(object sender, RoutedEventArgs e) { linePressed = true; } private void inkCanvas1_MouseUp(object sender, MouseButtonEventArgs e) { FrameworkElement fe = sender as FrameworkElement; EndPosition = e.MouseDevice.GetPosition(fe); if (linePressed) { this.inkCanvas1.EditingMode = InkCanvasEditingMode.Ink; Line l = new System.Windows.Shapes.Line(); l.X1 = StartPosition.X; l.X2 = EndPosition.X; l.Y1 = StartPosition.Y; l.Y2 = EndPosition.Y; l.Stroke = Brushes.Red; l.StrokeThickness = 5; inkCanvas1.Children.Add(l); } } 

As a result, lines are drawn as follows:
Result

How can I fix this?

PS I tried to display the EndPosition coordinates at the time of drawing in the console, but without success.

  • What is your fe ? - VladD
  • @VladD: FrameworkElement fe = sender as FrameworkElement; Interestingly, the MouseDown event never fires. If the author would use the debugger, he would immediately see it - Andrew NOP
  • @Andrey: No, well, I see it, I wonder what kind of object it really is. But if MouseDown does not come, then it is clear what the problem is. - VladD
  • @Andrey there inkCanvas. Replaced e.MouseDevice.GetPosition(fe); on e.MouseDevice.GetPosition(inkCanvas1); - the same result - Moonlight
  • Well, I understood how to fix it, but somehow it is very crutch. - Andrei NOP

1 answer 1

Set the EditingMode="None" property to EditingMode="None" and do not change it in the code. In EditingMode="Ink" mode EditingMode="Ink" item does not track the MouseDown event MouseDown

  • Then a logical question arises, but what about InkCanvas? - VladD
  • @VladD, I don't know why he is the author, because in Ink mode, the pen trace is drawn, what does the author want to do - it’s not clear and draw a line and a trace from the cursor too? Or is he a hacker there - the color of the pen line is set equal to the background color, on the screen there are no traces from the cursor ... - Andrei NOP
  • @ Andrew corrected, missed the moment that you need to change the mode, thanks - Moonlight
  • @Andrey: He himself draws, the question is, how then can one draw something drawn? - VladD
  • @VladD, from the Strokes property? In general, of course, since we have InkCanvas, then we need to draw with Stroke , not with lines ... - Andrey NOP