gpt4 book ai didi

c# - 当用户选择文本时更改 TextBox 突出显示颜色?

转载 作者:可可西里 更新时间:2023-11-01 08:29:26 28 4
gpt4 key购买 nike

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

Selected text in Outlook

TextBox selected text by user

每个人都说我需要覆盖 onPaint 方法,但我不知道该怎么做。 RichTextbox selectedbackground 颜色不是解决方案,因为它会更改文本的颜色,而不是在用户选择它时。

最佳答案

作为一种选择,您可以依赖 ElementHost承载 WPF TextBox 控件的 Windows 窗体控件。然后为 WPF TextBox 控件设置 SelectionBrushSelectionOpacity

示例

在下面的示例中,我创建了一个 Windows 窗体 UserControl,其中包含一个 ElementHost 以托管 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; }
}
}

引用程序集

这里是需要引用的程序集:PresentationCorePresentationFrameworkWindowsBaseWindowsFormsIntegration

关于c# - 当用户选择文本时更改 TextBox 突出显示颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com