Disable the selection highlight in RichTextBox or

2019-05-04 09:14发布

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.

1条回答
贼婆χ
2楼-- · 2019-05-04 10:01

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.

查看更多
登录 后发表回答