views:

268

answers:

2

I am writing a custom control based on RichTextBox that needs the ability to process MouseLeftButtonDown events but must not allow user-initiated selection (I'm doing everything programmatically).

I tried setting a flag in MouseLeftButtonDown to track dragging and then continuously setting the RichTextBox.Selection to nothing in the MouseMove event but the move event isn't fired until after I release the mouse button.

Any ideas on how to solve this? Thanks.

A: 

Have you tried e.Handled = true in your event handler to see if that gets you the desired behaviour.

AnthonyWJones
The initial solution I was thinking of works, my problem was I was not overriding RichTextBox.OnMouseLeftButtonUp(). I appreciate your help.
David
A: 

Here's the solution I came up with:

public class CustomRichTextBox : RichTextBox
{
    private bool _selecting;

    public CustomRichTextBox()
    {
        this.MouseLeftButtonDown += (s, e) =>
        {
            _selecting = true;
        };
        this.MouseLeftButtonUp += (s, e) =>
        {
            this.SelectNone();
            _selecting = false;
        };
        this.KeyDown += (s, e) =>
        {
            if (e.Key == Key.Shift)
                _selecting = true;
        };
        this.KeyUp += (s, e) =>
        {
            if (e.Key == Key.Shift)
               _selecting = false;
        };
        this.SelectionChanged += (s, e) =>
        {
            if (_selecting)
                this.SelectNone();
        };
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);
        e.Handled = false;
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonUp(e);
        e.Handled = false;
    }

    public void SelectNone()
    {
        this.Selection.Select(this.ContentStart, this.ContentStart);
    }
}
David