当用户选择文本时,更改TextBox高亮显示的颜色吗? [英] Change the TextBox highlight color when a user selects text?
问题描述
我一直在寻找一种在用户选择文本时更改文本框突出显示颜色的方法.Windows使用蓝色作为默认颜色.例如,在Microsoft Outlook上,当您编写邮件并选择(突出显示)文本时,背景色为灰色.
I've been looking for the way to change the textbox highlight color when a user select text. Windows uses blue as default color. For example, on Microsoft Outlook, when you write a mail and select (highlight) text, the back color is gray.
每个人都说我需要重写onPaint方法,但我不知道该怎么做.RichTextbox选定的背景颜色不是解决方案,因为它会更改文本的颜色,而不是在用户选择时更改颜色.
Everybody said that I need to override onPaint method but i don't know how exactly to do that. The RichTextbox selectedbackground color is not the solution because it changes the color for the text, not when the user selects it.
推荐答案
As an option, you can rely on an ElementHost
Windows Forms control to host a WPF TextBox
control. Then for the WPF TextBox
control, set SelectionBrush
and SelectionOpacity
.
示例
在下面的示例中,我创建了一个Windows窗体 UserControl
,其中包含一个 ElementHost
来承载WPF TextBox
控件.然后,对于WPF TextBox
控件,设置 SelectionBrush
和 SelectionOpacity
.
In the following example I've created a Windows Forms UserControl
containing an ElementHost
to host a WPF TextBox
control. Then for the WPF TextBox
control, set SelectionBrush
and SelectionOpacity
.
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Media;
public class MyWPFTextBox : System.Windows.Forms.UserControl
{
private ElementHost elementHost = new ElementHost();
private TextBox textBox = new TextBox();
public MyWPFTextBox()
{
textBox.SelectionBrush = new SolidColorBrush(Colors.Gray);
textBox.SelectionOpacity = 0.5;
textBox.TextAlignment = TextAlignment.Left;
textBox.VerticalContentAlignment = VerticalAlignment.Center;
elementHost.Dock = System.Windows.Forms.DockStyle.Fill;
elementHost.Name = "elementHost";
elementHost.Child = textBox;
textBox.TextChanged += (s, e) => OnTextChanged(EventArgs.Empty);
Controls.Add(elementHost);
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
}
参考程序集
这里是必需的引用程序集: PresentationCore
, PresentationFramework
, WindowsBase
, WindowsFormsIntegration
.
Here are required referenced assemblies: PresentationCore
, PresentationFramework
, WindowsBase
, WindowsFormsIntegration
.
这篇关于当用户选择文本时,更改TextBox高亮显示的颜色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!