Limit the max number of chars per line in a textbox

前端 未结 5 1856
慢半拍i
慢半拍i 2021-01-25 23:24

Say I have the following:



        
5条回答
  •  后悔当初
    2021-01-25 23:57

    I do not really think that you can do this while wrapping because wrapping would change the current line to fit the TextBox. Even while using Notepad, you can never view the Status Bar while enabling the Word Wrap as it will be difficult to get the current line index and its length while wrapping.

    I've managed to set the maximum characters per line while the TextWrapping property is set to NoWrap. You'll first need to get the length of the current line index. Then, in case it's 59 or more, handle the input.

    Example

    
    
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        //Initialize a new int of name CurrentLine to get the current line the user is on
        int CurrentLine = textBox1.GetLineIndexFromCharacterIndex(textBox1.Text.Length);
    
        //Continue if the length of the current line is more or equal to 59
        if (textBox1.GetLineLength(CurrentLine) >= 59) 
        {
            //Don't insert the character
            e.Handled = true; 
        }
    }
    

    Thanks,
    I hope you find this helpful :)

提交回复
热议问题