Search code examples
c#richtextbox

C# RichTextBox disable auto block selection


I can't make partial selection for text in RichTextBox, how to disable the auto selection?

enter image description here

this.txtMSInput = new System.Windows.Forms.RichTextBox();
this.txtMSInput.DetectUrls = false;
this.txtMSInput.Location = new System.Drawing.Point(6, 31);
this.txtMSInput.Name = "txtMSInput";
this.txtMSInput.Size = new System.Drawing.Size(279, 202);
this.txtMSInput.TabIndex = 43;
this.txtMSInput.Text = "";

Solution

  • Found the answer, this is RichTextBox bug.

    from https://stackoverflow.com/a/3679036/10767810

    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.