多色文本框 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10587715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-color TextBox C#
提问by Wizard
I want show text in textbox in 2 colors, for example 1 line red 2 blue, if I use name.ForeColor = Color.Red;all text change color, but I want that will change only 1 line color.
我想在文本框中以 2 种颜色显示文本,例如 1 行红色 2 蓝色,如果我使用name.ForeColor = Color.Red;所有文本更改颜色,但我希望只更改 1 行颜色。
采纳答案by John Koerner
You need to use a RichTextBox.
您需要使用RichTextBox。
You can then change the textcolor by selecting text and changing the selection color or font.
然后,您可以通过选择文本并更改选择颜色或字体来更改文本颜色。
richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Red;
回答by animaonline
Use a RichTextBox for that, here is an extension method by Nathan Baulch
为此使用 RichTextBox,这是 Nathan Baulch 的扩展方法
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
Read more here
在这里阅读更多
回答by Danny Varod
First of all, the details + tags you provided are not sufficient - C# doesn't have one specific UI framework, it has a few: WPF, Winforms, ASP.NET, Silverlight.
首先,你提供的细节 + 标签是不够的——C# 没有一个特定的 UI 框架,它有几个:WPF、Winforms、ASP.NET、Silverlight。
Second of all, you can not do this with a regular textbox control in any of the above. You will need to find/create a custom UI control which has a different behaviour or use a more advanced control e.g. a rich text box.
其次,您不能使用上述任何一种中的常规文本框控件来执行此操作。您将需要查找/创建具有不同行为的自定义 UI 控件或使用更高级的控件,例如富文本框。
回答by berta
Here is an example with a Fontdialog and Colordialog.
这是一个带有 Fontdialog 和 Colordialog 的示例。
void TextfarbeToolStripMenuItemClick(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
richTextBox1.ForeColor = colorDialog1.Color;
listBox1.ForeColor = colorDialog1.Color;
}
void FontsToolStripMenuItemClick(object sender, EventArgs e)
{
fontDialog1.ShowDialog();
richTextBox1.Font = fontDialog1.Font;
listBox1.Font = fontDialog1.Font;
}
void HintergrundfarbeToolStripMenuItemClick(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
richTextBox1.BackColor = colorDialog1.Color;
listBox1.BackColor = colorDialog1.Color;
}

