c# - 我可以使用这段旧代码来更改富文本框中一行的文本颜色吗?
问题描述
在不存在错误的情况下,RichTextBox 字段中的文本颜色不会改变。
这是一个简单的基于文本的 c# 游戏(我很新)。我在网上尝试了多种不同的解决方案,但无济于事。我发现这个 2006 年的旧代码似乎没有错误但似乎没有改变任何东西。我假设发生故障的地方是文本实际上并没有被选中,尽管语法似乎是正确的。我尝试以读取文本长度的形式插入一些调试代码,它给出了正确的数字——在这个例子中,选择长度显示为 26,这是正确的。
void AppendText(RichTextBox box, Color color, string text)
{
int start = box.TextLength;
box.AppendText(text);
int end = box.TextLength;
//Textbox may transform chars, so (end-start) != text.Length
box.Select(start, end - start);
{
box.SelectionColor = color;
}
box.SelectionLength = 0;
box.Text += Environment.NewLine;
}
//which is being called by:
AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
我希望它将此文本更改为红色。它不会改变文本颜色。
有趣的是,如果(而不是 box.SelectionColor)插入 box.Forecolor,它确实会将整个文本框更新为红色 - 让我相信选择部分是断开的链接。
运行此代码时不存在错误。
解决方案
我读到使用+=
附加文本会重置所有应用的颜色,所以无论您的代码的早期部分可能取得成功,它们很可能会被最后一行抹去!
我在评论中链接了一个相关的 SO 问题;它似乎与您的大致相似,但 225 多人似乎很欣赏它的工作原理。它是一种扩展方法,因此您需要在静态类中声明它,但随后它就可以在您拥有的任何 RichTextBox 上巧妙地使用..
编辑:所以您说它有效,但您不期待更改所有代码
我猜你的代码是这样的:
AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
AppendText(rtbMessages2, Color.Blue, "Yarr Matey, this be a test 2");
AppendText(rtbMessages3, Color.Green, "Yarr Matey, this be a test 3");
要么改变你的 AppendText 方法(他们都在调用),所以它调用扩展:
public static class RichTextBoxExtensions
{
//this is THE EXTENSION method
public static void AppendText(this RichTextBox box, string text, Color color)
{
...
}
}
//this is YOUR code
void AppendText(RichTextBox box, Color color, string text)
{
//call THE EXTENSION code
box.AppendText(color, text);
}
//now your code, calls your code, calls the extension
AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
或者在您的代码中运行查找替换:
FIND: AppendText\((\w+), (.*)
REPL: $1.AppendText($2)
AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$1 $2
它将转换您的所有代码:
FROM: AppendText(rtb1, color, text);
TO: rtb1.AppendText(color, text);
推荐阅读
- v8 - V8 modules exporting functions that call into c++
- python - 将 jupyter notebook 更新到 python 3.7
- apache-fop - 使用 FOP 将 SVG 放入 PDF 可在本地计算机上工作,但不能在服务器上工作
- javascript - Firebase 身份验证错误:auth/invalid-credential
- c# - 如何验证正则表达式
- reactjs - 将 Json 数据映射到反应中的下拉列表
- amazon-web-services - 在我的 AWS Deep Learning AMI EC2 实例上删除并重新安装 Anaconda,现在无法进入预配置的深度学习环境
- python-2.7 - 使用 PySpark 从表中识别分区键列
- php - 如何使用 php 代码在 GCE 上创建凭证(用于谷歌表格)?
- mysql - 将 SQL 查询结果卸载到变量而不是 shell 脚本上的文件