Disable the selection highlight in RichTextBox or TextBox

ⅰ亾dé卋堺 提交于 2019-12-05 11:50:57

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!