如何限制要在文本框中粘贴的字符数?

时间:2013-07-19 03:23:19

标签: c# winforms

我需要限制要在多行文本框中粘贴的字符数。

假设这是我要在文本框中粘贴的字符串:

  

美好的一天女士们和男士们!   
  我只是想知道   

如果可以,请提供帮助。

规则是最大字符PER LINE是10,最大ROWS是2.应用规则,粘贴文本应该只是这样:

  

美好的一天L.   
  我只是想

5 个答案:

答案 0 :(得分:5)

没有自动做什么。您需要在文本框中处理TextChanged事件,并手动解析更改的文本以将其限制为所需的格式。

private const int MaxCharsPerRow = 10;
private const int MaxLines = 2;

private void textBox1_TextChanged(object sender, EventArgs e) {
    string[] lines = textBox1.Lines;
    var newLines = new List<string>();
    for (int i = 0; i < lines.Length && i < MaxLines; i++) {
        newLines.Add(lines[i].Substring(0, Math.Min(lines[i].Length, MaxCharsPerRow)));
    }
    textBox1.Lines = newLines.ToArray();
}

答案 1 :(得分:3)

您可以抓住WM_PASTE邮件(发送给您的TextBox)自行处理:

public class MyTextBox : TextBox
{
    int maxLine = 2;
    int maxChars = 10;
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x302)//WM_PASTE
        {
            string s = Clipboard.GetText();
            string[] lines = s.Split('\n');
            s = "";
            int i = 0;
            foreach (string line in lines)
            {
                s += (line.Length > maxChars ? line.Substring(0, maxChars) : line) + "\r\n";
                if (++i == maxLine) break;
            }
            if(i > 0) SelectedText = s.Substring(0,s.Length - 2);//strip off the last \r\n
            return;
        }
        base.WndProc(ref m);            
    }
}

答案 2 :(得分:1)

您可以通过以下方式实现此目的。将文本框的maximum length设置为22

textBox1.MaxLength = 22;

在文本更改事件中执行以下操作

private void textBox1_TextChanged(object sender, EventArgs e)
{
     if (textBox1.Text.Length == 10)
     {
           textBox1.AppendText("\r\n");
     }
}

这将自动进入10个字符后的下一行

答案 3 :(得分:0)

为什么不使用剪贴板数据来实现此目的。以下是一个小例子。

String clipboardText = Clipbard.GetText( );

// MAXPASTELENGTH - max length allowed by your program

if(clipboardText.Length > MAXPASTELENGTH)
{

   Clipboard.Clear(); 

   String newClipboardText = clipboardText.Substring(0, MAXPASTELENGTH);

   // set the new clipboard data to the max length 
   SetData(DataFormats.Text, (Object)newClipboardText );

}

现在可以随意粘贴数据,数据应修剪到程序允许的最大长度。

答案 4 :(得分:-2)

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text.Length == 10)
        {
            textBox1.MaxLength = 10;
            //MessageBox.Show("maksimal 10 karakter");
        }
    }
相关问题