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

问题描述 投票:8回答:5

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

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

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

如果可以的话,请帮忙。

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

美好的一天L. 我只是想

c# winforms
5个回答
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();
}

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);            
    }
}

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个字符后自动进入下一行


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 );

}

现在将数据粘贴到您喜欢的任何位置,数据应修剪到程序允许的最大长度。


-2
投票
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text.Length == 10)
        {
            textBox1.MaxLength = 10;
            //MessageBox.Show("maksimal 10 karakter");
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.