【问题标题】:Changing RichTextBox to a Label [duplicate]将 RichTextBox 更改为标签 [重复]
【发布时间】:2013-04-04 03:56:32
【问题描述】:

我正在使用富文本框作为我的应用程序的标签。文本框是只读的,但可以选择其内容。如何让用户在只读的富文本框中无法选择文本?

当我禁用控件时,无法选择文本但我失去了颜色,因为它们变成灰色(禁用)。如何在不禁用富文本框控件的情况下禁用文本选择?

仅供参考:我使用富文本框作为标签,因为我需要将字符串中需要显示给用户的一个单词的前景色更改为红色。我使用this SO文章和以下方法来做到这一点。

string word = "red";
int start = richTextBox1.Find(word);
if (start >= 0) {
    richTextBox1.Select(start, word.Length);
    richTextBox1.SelectionColor = Color.Red;
}

编辑:顺便说一句,这是 C# WinForm

【问题讨论】:

  • 如果文本是可选择的有什么区别?他们无法编辑或删除它,因此不会产生负面影响。
  • @CodyGray 你是对的。但是,它的外观应该是一个标签。这就是我尝试这样做的原因。
  • 顺便问一下,这是 WinForms 还是 WPF?您应该这样标记它以避免歧义(因为两者都有RichTextBox)。
  • stackoverflow.com/questions/3805545/… 接受的答案效果很好。谢谢@Damith。

标签: c# .net winforms richtextbox


【解决方案1】:

只需处理选择,并将其恢复为“无”:

// so you have colour (set via the Designer)
richTextBox.Enabled = true;

// so users cannot change the contents (set via the Designer)
richTextBox.ReadOnly = true;

// allow users to select the text, but override what they do, IF they select the text (set via the Designer)
richTextBox.SelectionChanged += new System.EventHandler(this.richTextBox_SelectionChanged);

// If the user selects text, then de-select it
private void richTextBox_SelectionChanged(object sender, EventArgs e)
{
    // Move the cursor to the end
    if (this.richTextBox.SelectionStart != this.richTextBox.TextLength)
    {
        this.richTextBox.SelectionStart = this.richTextBox.TextLength;
    }
}

取自:http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/d1132ee5-acad-49f3-ae93-19d386fe2d12/

(顺便说一句,一点点of searching 有很长的路要走。)

【讨论】:

  • 每当用户去选择某些东西时,这是否有一个难看的部分选择闪烁?
  • @CodyGray 我还没有测试过它,但我怀疑它可以。但是,如果 OP 想要将控件用于它不是为它设计的东西,我想你必须接受不太完美的行为。
  • @JonathonReinhart 我提到了它。而且我还使用了 MSDN 文章中接受的答案。但背面颜色保持不变。灰色禁用。
  • @CodyGray(无关):someone needs your help
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多