2
如果我有一个RichTextBox并希望第一行的输出是大写字母和粗体的字体,而下一行恰恰相反,我该怎么办?使用大写字母和粗体格式化RichTextBox的第一行
输出是这样的:
MY NAME IS
戴安娜
我的地址是
中国
如果我有一个RichTextBox并希望第一行的输出是大写字母和粗体的字体,而下一行恰恰相反,我该怎么办?使用大写字母和粗体格式化RichTextBox的第一行
输出是这样的:
MY NAME IS
戴安娜
我的地址是
中国
嘿试试这个,它的工作原理,但你可能看到的文字闪烁的第二个如果用户类型真的很快,例如按住“Enter”等。
private void Form_Load(object sender, EventArgs e)
{
// append the function to the RichTextBox's TextChanged event
MyRichTextBox.TextChanged += Capitalize_Bold_FirstLine;
}
private void Capitalize_Bold_FirstLine(object sender, EventArgs e)
{
RichTextBox box = sender as RichTextBox;
if (box != null && box.Text != "")
{
// get the current selection text of the textbox
int ss = box.SelectionStart;
int sl = box.SelectionLength;
// get the position where the first line ends
int firstLineEnd = box.Text.IndexOf('\n');
if (firstLineEnd < 0)
firstLineEnd = box.Text.Length;
// split the lines
string[] lines = box.Text.Split('\n');
// capitalize the first line
lines[0] = lines[0].ToUpper();
// join them back and set the new text
box.Text = String.Join("\n", lines);
// select the first line and make it bold
box.SelectionStart = 0;
box.SelectionLength = firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Bold);
// select the rest and make it regular
box.SelectionStart = firstLineEnd;
box.SelectionLength = box.Text.Length - firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Regular);
// go back to what the user had selected
box.SelectionStart = ss;
box.SelectionLength = sl;
}
}
谢谢,您的公关ogram完美地工作,只有一行错误,然后我关闭了错误,并已正常工作。错误是这样的行:// endof.Text = firstLineEnd.ToString(); – diana 2011-06-03 13:10:34
@diana没问题,对不起,我使用该行进行调试,并忘记将其初始化,我在编辑帖子后将其取出。 – 2011-06-03 13:21:37