自动换行,多行TextBox(Winforms)上的火事件

时间:2012-08-06 09:35:53

标签: c# winforms

因此,我编写了一种方法来限制允许在多行文本框中写入的行数(因为这不是Microsoft提供的属性)。该方法适用于所有情况,除非发生wordwrap事件(键入单个char时,或从剪贴板粘贴文本时)。我现在的代码:

    protected void limitLineNumbers(object sender, KeyPressEventArgs e, UInt16 numberOfLines)
    {
        int[] specialChars = { 1, 3, 8, 22, 24, 26 }; // ctrl+a, ctrl+c, backspace, ctrl+v, ctrl+x, ctrl+z
        bool found = false;
        string lastPressedChar = "";
        TextBox temp = (TextBox)sender;

        foreach (int i in specialChars)
        {
            if (i == (int)e.KeyChar)
                found = true;
        }
        if (!found)
            lastPressedChar = e.KeyChar.ToString(); // Only add if there is a "real" char

        int currentLine = temp.GetLineFromCharIndex(temp.SelectionStart) + 1;
        int totalNumberOfLines = temp.GetLineFromCharIndex(temp.TextLength) + 1;

        if ((int)e.KeyChar == 1)
            temp.SelectAll();

        // Paste text from clipboard (ctrl+v)
        else if ((int)e.KeyChar == 22)
        {
            string clipboardData = Clipboard.GetText();
            int lineCountCopiedText = 0;
            foreach (char c in clipboardData)
            {
                if (c.Equals("\n"))
                    ++lineCountCopiedText;
            }
            if ((currentLine > numberOfLines || (totalNumberOfLines + lineCountCopiedText) > numberOfLines))
                e.Handled = true;
        }
        // Carrige return (enter)
        else if ((int)e.KeyChar == 13)
        {
            if ((currentLine + 1) > numberOfLines || (totalNumberOfLines + 1) > numberOfLines)
                e.Handled = true;
        }

        // Disallow
        else if ((currentLine > numberOfLines) || (totalNumberOfLines > numberOfLines))
            e.Handled = true;
    }

那么,你们有什么想法让我的方法更完整吗?最好的解决方案是捕获wordwrap事件,但据我所知,这是不可能做到的?另一种解决方案是删除文本行,如果超过允许的最大值。

或者它可能是一个比我想出的更好的解决方案吗?感谢您的意见。

0 个答案:

没有答案