禁用 RichTextBox 或 TextBox 中的选择突出显示

Disable the selection highlight in RichTextBox or TextBox

如何在我的 Windows 表单应用程序中禁用 RichTexBoxTextBox 的选择突出显示,如图所示。

我需要将选择突出显示颜色从 Blue 更改为 White,因为我需要一直隐藏 TextBoxRichTextBox 中的选择。我尝试使用 RichTextBox.HideSelection = true,但它没有像我预期的那样工作。

你可以处理 WM_SETFOCUS message of RichTextBox and replace it with WM_KILLFOCUS.

在下面的代码中,我创建了一个 ExRichTextBox class 具有 Selectable 属性:

  • Selectable:启用或禁用选择突出显示。如果将 Selectable 设置为 false,则选择突出显示将被禁用。默认情况下启用。

说明:它不会使控件只读,如果需要将其设为只读,还应将ReadOnly 属性设置为true及其BackColorWhite.

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);
    }
}

您可以对 TextBox 控件执行相同的操作。