Limit number of characters per line

5

Is it possible to limit the number of characters per line of a% multiline% using Windows Forms C # and .Net 3.5?

    
asked by anonymous 10.02.2014 / 11:50

4 answers

3

I created an algorithm here in the TextBox KeyPress, it limits the number of characters in each line and forces the user to type enter to change the line:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    int tamanhoMaximoPorLinha = 10; 
    int[] keysLiberadas = { (int)Keys.Enter, (int)Keys.Back };

    int posicaoAtual = textBox1.SelectionStart;
    int linhaAtual = textBox1.GetLineFromCharIndex(posicaoAtual);

    if (textBox1.Lines.Length == 0)
    {
        if (textBox1.Text.Length > tamanhoMaximoPorLinha && !keysLiberadas.Contains((int)e.KeyChar))
        {
            e.Handled = true;
        }
    }
    else if (textBox1.Lines[linhaAtual].Length > tamanhoMaximoPorLinha && !keysLiberadas.Contains((int)e.KeyChar))
    {
        e.Handled = true;
    }
}

e.Handled = true; prevents typing that character.

    
10.02.2014 / 13:22
2

You can override AppendText and Text in a derived class.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class TextBoxExt : TextBox
    {
        new public void AppendText(string text)
        {
            if (Text.Length == MaxLength)
                return;
            base.AppendText(Text.Length + text.Length > MaxLength
                                ? text.Substring(0, (MaxLength - Text.Length))
                                : text);
        }

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set {
                base.Text = !string.IsNullOrEmpty(value) && value.Length > MaxLength
                                ? value.Substring(0, MaxLength)
                                : value;
            }
        }

        // Clearing top X lines with high performance
        public void ClearTopLines(int count)
        {
            if (count <= 0)
                return;
            if (!Multiline)
            {
                Clear();
                return;
            }

            var txt = Text;
            var cursor = 0;
            var brkCount = 0;

            while (brkCount < count)
            {
                int brkLength;
                var ixOf = txt.IndexOfBreak(cursor, out brkLength);
                if (ixOf < 0)
                {
                    Clear();
                    return;
                }
                cursor = ixOf + brkLength;
                brkCount++;
            }
            Text = txt.Substring(cursor);
        }
    }

    public static class StringExt
    {
        public static int IndexOfBreak(this string str, out int length)
        {
            return IndexOfBreak(str, 0, out length);
        }

        public static int IndexOfBreak(this string str, int startIndex, out int length)
        {
            if (string.IsNullOrEmpty(str))
            {
                length = 0;
                return -1;
            }
            var ub = str.Length - 1;
            if (startIndex > ub)
            {
                throw new ArgumentOutOfRangeException();
            }
            for (var i = startIndex; i <= ub; i++)
            {
                int intchr = str[i];
                switch (intchr)
                {
                    case 0x0D:
                        length = i < ub && str[i + 1] == 0x0A ? 2 : 1;
                        return i;
                    case 0x0A:
                        length = 1;
                        return i;
                }
            }
            length = 0;
            return -1;
        }
    }
}
    
10.02.2014 / 12:49
1

I think creating a textchanged event and adding an if statement counts.

int jumpline = 40; //A cada 40 caracteres.
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{    
    if(textbox99.text.Length%jumpline ==0){
        textbox99.text += "\r\n";
    }
}
    
10.02.2014 / 13:21
0

Good afternoon, I know that the question has already been answered, but how these answers helped me solve my problem, I leave here shared more information. I used these 2 events in sets for better resolution in my case. The first one has the function of:

1. Set the maximum size of richtextbox to 500.

2. Sets the line size to 75.

3.

If the word exceeds the size of the line, it is transferred to the line below.

4. If the maximum size of the richtextbox is exceeded, a msg is displayed.

5. Restricts special characters by inserting space in the current position.

    private void rtxbAnaliseOp_TextChanged(object sender, EventArgs e)
    {
        bool ok = false;
        int i =  rtxbAnaliseOp.Text.Length -1;
        rtxbAnaliseOp.MaxLength = 500;
        try
        {   
            //tamanho do texto dividido pela quantidade de linhas
            if ((rtxbAnaliseOp.Text.Length / rtxbAnaliseOp.Lines.Length) >= 75)
            {
                //Nesse bloco é verificado o tamanho da palavra escrita após exceder o tamanho máximo da linha,
                //contando as casas decimais anteriores até achar o intervalo da palavra "espaço" o código insere Enter para pular de linha.
                while (ok == false)
                {
                    string x = rtxbAnaliseOp.Text.Substring(i, 1);
                    if (x == " ")
                    {
                        ok = true;
                        rtxbAnaliseOp.Text = string.Format(rtxbAnaliseOp.Text.Insert(++i, "\n"));
                        rtxbAnaliseOp.SelectionStart = rtxbAnaliseOp.Text.Length;
                    }
                    else
                        i--;
                }
            } 
            if (rtxbAnaliseOp.Text.Length >= 500)
            {                    
                // Verifica se o tamanho do texto é maior que a quantidade maxima de carateres disponíveis.
                if (rtxbAnaliseOp.Text.Length >= rtxbAnaliseOp.MaxLength)
                {
                    // Alerta o usuário que o maximo de carateres já foi escrito.
                    MessageBox.Show("Aleta! Você excedeu o limite de caracteres disponíveis");
                }                                        
            }

            //string pattern = @"[^0-9a-záéíóúàèìòùâêîôûãõç\s]";
            string pattern = @"[^0-9a-zA-Z\s]";
            string replacement = "";

            Regex rgx = new Regex(pattern);                
            string letra = rtxbAnaliseOp.Text.Substring(i, 1);

            //Verifica existência de caracteres especiais.
            if ( Regex.IsMatch(letra, pattern ))
            {
                MessageBox.Show("Aleta! Este campo não permite a inserção de Caracteres especiais");

                //Remove caracteres especiais Expressoes Regulares(Nesse caso nao aceita nada que não seja letras, numeros e espaço representado por "\s").
                rtxbAnaliseOp.Text = rgx.Replace(rtxbAnaliseOp.Text, replacement);
                rtxbAnaliseOp.SelectionStart = (rtxbAnaliseOp.Text.Length);
                //    rtxbAnaliseOp.Text = Regex.Replace(rtxbAnaliseOp.Text, "[^0-9a-zA-Z]", "");   
                //    rtxbAnaliseOp.Text = Regex.Replace(rtxbAnaliseOp.Text, pattern, replacement);
            }
        }
        catch (ArgumentOutOfRangeException)
        {
            rtxbAnaliseOp.Text = rtxbAnaliseOp.Text + string.Format("\n");
            rtxbAnaliseOp.SelectionStart = (rtxbAnaliseOp.Text.Length);
        }
        catch (DivideByZeroException)
        { }
    }

In this second case is our friend's code:

  

Maicon Carraro

But in my case I had to change the checking from IF to: if (rtxbAnaliseOp.Text.Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar))) because keyLiberada did not contain the String.Contains method.

    private void rtxbAnaliseOp_KeyPress(object sender, KeyPressEventArgs e)
    {
        //limita a quantidade de caracteres em cada linha e obriga ao usuário digitar enter para que mude de linha.
        int tamanhoMaximoPorLinha = 75;            
        int keyLiberada = (int)Keys.Enter;
        int posicaoAtual = rtxbAnaliseOp.SelectionStart;
        int linhaAtual = rtxbAnaliseOp.GetLineFromCharIndex(posicaoAtual);

        if (rtxbAnaliseOp.Lines.Length == 0)
        {
            if (rtxbAnaliseOp.Text.Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar)))
            {
                e.Handled = true;
            }
        }
        else if (rtxbAnaliseOp.Lines[linhaAtual].Length > tamanhoMaximoPorLinha && !keyLiberada.ToString().Contains(Convert.ToString((int)e.KeyChar)))
        {
            e.Handled = true;
        }
    }

Thanks again and I hope to have helped.

    
10.09.2018 / 22:34