Search code examples
c#winformstextboxselectionrichtextbox

Disable the selection highlight in RichTextBox or TextBox


How can I disable the selection highlight of RichTexBox or TextBox in my Windows Forms Application as shown in the image.

enter image description here

I need to change selection highlight color from Blue to White, because I need to hide selection in TextBox or RichTextBox all the time. I tried to use RichTextBox.HideSelection = true, but it doesn't not work as I expect.


Solution

  • You can handle WM_SETFOCUS message of RichTextBox and replace it with WM_KILLFOCUS.

    In the following code, I've created a ExRichTextBox class having Selectable property:

    • Selectable: Enables or disables selection highlight. If you set Selectable to false then the selection highlight will be disabled. It's enabled by default.

    Remarks: It doesn't make the control read-only and if you need to make it read-only, you should also set ReadOnly property to true and its BackColor to White.

    public class ExRichTextBox : RichTextBox
    {
        public ExRichTextBox()
        {
            Selectable = true;
        }
        const int WM_SETFOCUS = 0x0007;
        const int WM_KILLFOCUS = 0x0008;
    
        ///<summary>
        /// Enables or disables selection highlight. 
        /// If you set `Selectable` to `false` then the selection highlight
        /// will be disabled. 
        /// It's enabled by default.
        ///</summary>
        [DefaultValue(true)]
        public bool Selectable { get; set; }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SETFOCUS && !Selectable)
                m.Msg = WM_KILLFOCUS;
    
            base.WndProc(ref m);
        }
    }
    

    You can do the same for TextBox control.