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