禁用 RichTextBox 或 TextBox 中的选择突出显示
如何在我的 Windows 窗体应用程序中禁用 RichTexBox
或 TextBox
的选择突出显示,如图所示.
How can I disable the selection highlight of RichTexBox
or TextBox
in my Windows Forms Application as shown in the image.
我需要将选择高亮颜色从 Blue
更改为 White
,因为我需要隐藏 TextBox
或 RichTextBox 一直.我尝试使用
RichTextBox.HideSelection = true
,但它没有像我预期的那样工作.
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.
您可以处理 WM_SETFOCUS
RichTextBox
的消息并将其替换为 WM_KILLFOCUS
.
You can handle WM_SETFOCUS
message of RichTextBox
and replace it with WM_KILLFOCUS
.
在下面的代码中,我创建了一个具有 Selectable
属性的 ExRichTextBox
类:
In the following code, I've created a ExRichTextBox
class having Selectable
property:
-
Selectable
:启用或禁用选择突出显示.如果您将Selectable
设置为false
,则选择突出显示将被禁用.默认情况下已启用.
-
Selectable
: Enables or disables selection highlight. If you setSelectable
tofalse
then the selection highlight will be disabled. It's enabled by default.
备注:它不会使控件只读,如果您需要将其设为只读,您还应该将 ReadOnly
属性设置为 true
及其BackColor
到 White
.
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);
}
}
您可以对 TextBox
控件执行相同操作.
You can do the same for TextBox
control.