当用户选择文本时,更改TextBox高亮颜色?

我一直在寻找在用户选择文本时更改文本框高亮颜色的方法。 Windows使用蓝色作为默认颜色。 例如,在Microsoft Outlook上,当您编写邮件并选择(突出显示)文本时,背面颜色为灰色。

Outlook中的选定文本

TextBox按用户选择文本

大家都说我需要覆盖onPaint方法,但我不知道究竟是怎么做的。 RichTextbox selectedbackground颜色不是解决方案,因为它更改了文本的颜色,而不是用户选择它时。

作为一个选项,您可以依靠ElementHost Windows窗体控件来托管WPF TextBox控件。 然后,对于WPF TextBox控件,设置SelectionBrushSelectionOpacity

在下面的示例中,我创建了一个包含ElementHost的Windows窗体UserControl来托管WPF TextBox控件。 然后,对于WPF TextBox控件,设置SelectionBrushSelectionOpacity

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

参考assembly

以下是必需的引用程序集: PresentationCorePresentationFrameworkWindowsBaseWindowsFormsIntegration

嗨,这里是更改选择颜色的代码,请记住,您必须存储当前颜色,然后一旦您更改颜色并关闭应用程序,您将需要恢复它,因为这会改变整体颜色计算机不仅仅适用于当前的流程。

  [DllImport("user32.dll")] static extern bool SetSysColors(int cElements, int[] lpaElements, uint[] lpaRgbValues); void ChangeSelectColour(Color color) { const int COLOR_HIGHLIGHT = 13; const int COLOR_HIGHLIGHTTEXT = 14; // You will have to set the HighlightText colour if you want to change that as well. //array of elements to change int[] elements = { COLOR_HIGHLIGHT }; List colours = new List(); colours.Add((uint)ColorTranslator.ToWin32(color)); //set the desktop color using p/invoke SetSysColors(elements.Length, elements, colours.ToArray()); }