bool IsKeyEnter = false; int maxLength = 80; //限制长度 private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) { //判断是否按下 Enter if (e.KeyChar == 13) { IsKeyEnter = true; } } private void richTextBox1_TextChanged(object sender, EventArgs e) { //不为Enter才时 if (!IsKeyEnter) { string[] aryTxt = this.richTextBox1.Text.Split(Environment.NewLine.ToCharArray()); List<string> listText = new List<string>(); //将字串由换行符号切成一个个的字串,再去判断各字串是否大于限制长度 foreach (string str in aryTxt) { //判断是否大于限制长度 if (str.Length > maxLength) { //判断大于限制长度的字串可切成几分 int splitCount = str.Length / maxLength; if (str.Length % maxLength != 0) { splitCount++; } //将字串放入 listText int index = 0; for (int i = 0; i < splitCount; i++) { if (str.Length >= index + maxLength) { listText.Add(str.Substring(index, maxLength)); } else { listText.Add(str.Substring(index)); } index += maxLength; } } else { listText.Add(str); } } //最后还原字串 string formatText = String.Empty; foreach(string str in listText) { formatText += str + Environment.NewLine; } formatText = formatText.Substring(0,formatText.LastIndexOf(Environment.NewLine)); this.richTextBox1.Text = formatText; this.richTextBox1.SelectionStart = richTextBox1.Text.Length; } IsKeyEnter = false; }
我是这样想的,嘻嘻!写一个函数:用Split('\n')获得一个包含每一行文本的字符串数组,然后用if判断,这个函数可以用TextChange事件来触发,下面是伪代码:String[] strs=richTextBox1.Text.Split('\n');foreach(String str in strs){if(str.length>80){MessageBox.show("对不起,您输入的字符已经超过80个!");}}