C# RichTextBox selection problem

I have a RichTextBox control on an application and here's my problem: when the application runs, if I start selecting with the mouse some of the characters inside a word and continue selecting outside it, the selection automatically includes the whole word in which I begun selection and any other words from which I want to select just a part, ms word-ish, if I'm not mistaken.

e.g.:

  • the text is: "Just another foobar"
  • what I want to select is: "Just ano[ther foo]bar" (the thing between the [])
  • what is actually selected: "Just [another foobar]"

The problem is just with mouse selecting, if I select text with the keyboard it works just fine. Also, the auto word select property of the control is turned off. Any idea why is that?


Solution 1:

There's a silly bug in the AutoWordSelection property implementation. The workaround is equally silly. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form, replacing the existing RTB.

using System;
using System.Windows.Forms;

public class FixedRichTextBox : RichTextBox {
    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        if (!base.AutoWordSelection) {
            base.AutoWordSelection = true;
            base.AutoWordSelection = false;
        }
    }
}

I left an annotation at the bottom of this MSDN Library page with the details of the bug.

Solution 2:

Maybe things have changed since this question was answered, but I have an even simpler solution:

Just add richTextBox1.AutoWordSelection = false; to the code.

Sounds crazy, but setting this to false in the properties-box does not work. You have to do it in the code, even if the property is already false. Then it works!