在C#中显示只读文本的最佳方法

7

当文本框的属性Enabled被设置为false或只读属性被设置为true时,显示的文本会呈现黑色底纹,这样并不方便阅读。

在Windows Forms中,有什么最简单的方法能够漂亮地展示只读文本呢?


相关帖子 - 使文本框不可编辑 - RBT
3个回答

7

当控件被锁定时,您无法覆盖ForeColor和BackColor属性吗?

如果无法实现,可以创建自己的文本框类来监听KeyUp事件,并在ReadOnly(或Locked)属性设置为true时拦截按键(防止其添加到文本中)。然后,您可以使用任何样式。


2
刚试了一下,是的,在将ReadOnly属性设置为True之后,确实可以将BackColor设置回白色。 - Andy Shellam
我确实在某个地方看到过这个作为解决这个问题的方法发布,而且它对我大部分是有效的,但由于某些原因,在实践中我有了一个问题。也许与无障碍有关?如果我记得,我会更新为什么我没有选择这条路(如果它对你有用,那还好,我猜:-)。 - Iain Collins
2
你不应该将颜色设置为黑色和白色。相反,应将它们设置为 BackColor = SystemColors.WindowForeColor = SystemColors.ControlText - Oliver

0

在Windows上,这似乎是一件非常糟糕的事情,具体取决于你想要达到的程度(例如,如果你希望文本可选择或不可选择,如果你希望能够进行文本格式设置)。

我在一段时间前发现了这个问题,但很幸运地在各种博客上找到了相当好的文档。看起来你可以使用RichTextBox,但创建事件处理程序以防止最终用户修改其内容。

例如,称为“myRichTextBox”的RichTextBox,然后您将希望在窗体的Designer.cs中添加以下内容:

this.myRichTextBox.SelectionChanged += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.DoubleClick += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.GotFocus += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.MyRichTextBox_LinkClicked);

然后您需要在表单中创建以下类似的方法:

public void MyRichTextBox_Deselect(object sender, EventArgs e)
{
    // When user tries to select text in the rich text box, 
    // set selection to nothing and set focus somewhere else.
    RichTextBox richTextBox = sender as RichTextBox;
    richTextBox.SelectionLength = 0;
    richTextBox.SelectionStart = richTextBox.Text.Length;
    // In this case I use an instance of separator bar on the form to switch focus to.
    // You could equally set focus to some other element, but take care not to
    // impede accessibility or visibly highlight something like a label inadvertently.
    // It seems like there should be a way to drop focus, perhaps to the Window, but
    // haven't found a better approach. Feedback very welcome.
    mySeperatorBar.Focus();
}

public void MyRichTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
{
    System.Diagnostics.Process.Start(e.LinkText);
}

显然,您可能不关心LinkClickedEventHandler()处理程序,但我确认希望具有此功能是相当普遍的,因为RichTextBox控件具有自动识别和着色URL的选项。

我不知道为什么似乎没有更优雅的解决方案,欢迎任何了解更好方法的人提供意见。


0

嗯... 使用标签? 为什么要使用文本框,并使其看起来可编辑,而实际上它并不是? 你想让用户感到困惑吗? 违反惯例的用户界面风格习语,自行承担风险。


我想显示大量从其他地方获取/生成的文本。我希望以易于阅读的方式显示它(就像此网站上的文本一样)。并且当文本超过一页时,我希望带有滚动条。 - Andrew Ducker
1
使用文本框允许用户选择要复制的文本。惯例规定,黑色文本在灰色背景上是只读的,但标准文本区域(白色背景上的黑色文本)也很常见。 - Kevin Kibler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接