-2

I add a function that adds text to FlowDocument when the mouse clicks. There is no Click event in FlowDocument, so I listen to FlowDocument.MouseLeftButtonDown and MouseLeftButtonUp and check whether the mouse moves between down and up. When I click the mouse left button, the text successfully adds. However, I can't select any text in the FlowDocument.

I tried PreviewMouseLeftButtonDown and PreviewMouseLeftButtonUp. The behavior is the same. Isn't there a PostMouseLeftButtonDown?

My Code:

        Point mouseDownPoint;
        private void doc_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            mouseDownPoint = Mouse.GetPosition(doc);
            e.Handled = true;
        }

        private void doc_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var mouseUpPoint = Mouse.GetPosition(doc);
            if ((mouseUpPoint - mouseDownPoint).Length < 8) /* add text */;
        }

Snowy
  • 59
  • 8
  • 1
    That's what e.Handled = true does. Wanting a mousedown to do two things is not a good idea. Maybe a right-click or a button, it isn't very obvious how this is useful. – Hans Passant Nov 14 '22 at 05:20
  • @HansPassant Internal select text behavior only invokes when a user drags mouse. Mouse down and up without moving in a `FlowDocument` will do nothing. This is not one operation to do two things. – Snowy Nov 14 '22 at 19:44

2 Answers2

0

The control handles the event internally.

If you register the event handler programmatically like this, your doc_MouseLeftButtonUp event handler should get invoked (note that last handledEventsToo parameter):

doc.AddHandler(ContentElement.MouseLeftButtonUpEvent, 
    (MouseButtonEventHandler)doc_MouseLeftButtonUp, true);

Note that you may also have to take care of the MouseLeftButtonUp that is raised by the control itself.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • No, without `e.Handled=true` in `MouseLeftButtonDown`, `doc_MouseLeftButtonUp` will not fire even register with `handledEventsToo=true`. – Snowy Nov 14 '22 at 19:41
  • So keep `e.Handler = true`? I didn't say that you should remove it. – mm8 Nov 16 '22 at 14:52
0

I found the solution. Listen to FlowDocument.MouseLeftButtonDown and do not use e.Handled=true and listen to FlowDocumentScrollViewer.PreviewMouseLeftButtonUp will get text selection and add text behavior at the same time.

Snowy
  • 59
  • 8