Vishwa
Vishwa

Reputation: 506

How to break line for a specific character in a richtextbox in c#

when we type in the richtextbox if the word is not finished but the line is finished, the whole word will go to the next line.so can someone tell me how to do it for a special character.it normally happens for space character but i want to make it for another character(Ascii one).

Upvotes: 0

Views: 232

Answers (1)

Sascha Hennig
Sascha Hennig

Reputation: 2572

Check in the KeyPress event if the line-break character of your choice was pressed:

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '-')
    {
        int curserPosition = richTextBox1.SelectionStart;
        richTextBox1.Text += "-\r\n";
        richTextBox1.SelectionStart = curserPosition + 2;
        e.Handled = true;
    }
}

If pasting strings into the RichTextBox you will need to parse the strings and replace the character with the character plus carriage return and linebreak characters:

string rtbText = string.Empty;
rtbText.Replace("-", "-\r\n");

If you want to ONLY break when the current line is full you will have to put in some more logic along the lines of:

if (richTextBox1.Lines[richTextBox1.Lines.Length - 1].Length > 100)
{
    // parse the string for the last occurance of "-" and insert a CRLF behind it
}

Upvotes: 1

Related Questions