eivour
eivour

Reputation: 1787

How to accept Ctrl+Enter as return while processing Enter event on a Textbox in WPF?

I'm making a chat window and I want to send the message when the user presses the Enter key on the TextBox. But I also want to let the user enter line breaks using Ctrl+Enter key.

The problem is when I set AcceptsReturn=True and the user presses the Enter key the KeyDown event fires after the TextBox appends a line break, so the sent message would always contain a line break at the end. Is there a way to disable the Enter key while still allowing Ctrl+Enter?

I came up with the ugliest way, which is when the Enter key is pressed first remove the letter before the cursor and then process it. But is there a better way?

Upvotes: 2

Views: 756

Answers (1)

Sheridan
Sheridan

Reputation: 69959

I'm not 100% sure of your requirements, so you may have to juggle this code about a bit, but you should be able to do what you want by setting the e.Handled property of the KeyEventArgs to false. According to the linked page, this:

Gets or sets a value that indicates the present state of the event handling for a routed event as it travels the route.

In plain English, that just means that we can stop it from being used any further. Try something like this:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter) // if Enter key is pressed...
    {
        // ... and Ctrl key is NOT... then ignore it
        if (Keyboard.Modifiers != ModifierKeys.Control) e.Handled = true;
    }
}

Upvotes: 4

Related Questions