Search code examples
c#winformstextbox

In c# textbox, how do I know the exact index location where I pressed the Enter key?


In c# textbox when enter key is pressed, how do you the index where it was pressed?

For example, I have a textbox named txtDesc and txtDesc currently contains the phrase

"The quick brown fox jumped over the lazy dog."

My cursor position is after the word "fox" and then I pressed the enter key...

How do I know which index position I pressed the enter key?

private void txtDesc_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //enter key is down
        //How do I know which index position I pressed the enter key?
    }
}

I should be able to get the index 19 since that's the position after the "fox".

I want that position so I can manually place html code "<br>" after the word "fox". Which is where I pressed the enter key...


Solution

  • On WinForms (controls found in System.Windows.Forms) the caret position can be found in the SelectionStart position when SelectionLength is 0. When SelectionLength is greater than 0 the caret can be at the start or end of the selection, which isn't particularly useful... but in this case it's probably not important.

    If you want to insert an HTML-style <BR> when a new line is being added, you'll need to juggle the content of the textbox slightly.

    Here's one way to do it (again, for WinForms projects):

    private void txtDesc_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode != Keys.Enter || e.Modifiers != 0)
            return;
    
        var (p, l) = (txtDesc.SelectionStart, txtDesc.SelectionLength);
    
        string newText = $"{txtDesc.Text[..p]}<br>\r\n{txtDesc.Text[(p + l)..]}";
    
        txtDesc.Text = newText;
        txtDesc.SelectionStart = p + 6;
        txtDesc.SelectionLength = 0;
        txtDesc.ScrollToCaret();
    
        e.SuppressKeyPress = true;
    }
    

    This allows you to split a line with Shift+Enter without inserting the <br> tag, and if you hit enter when there's an active selection it will replace the selected text with the tag.