Search code examples
wpftextboxkeydown

WPF: Convert Ctrl+Enter to Enter on a TextBox


I have a multiline textbox on which Ctrl+Enter triggers a specific action. Enter, obviously, creates a new line in the textbox.

Now I would like to invert the two functionalities, i.e. Ctrl+Enter should create a new line and Enter should trigger my specific action. Everything works fine, except where I need to create a new line with Ctrl-Enter.

I tried this solution: How can I programmatically generate keypress events in C#? It doesn't work however, because when I raise a (Preview)Keydown/Up for the Enter key, the Ctrl key is still pressed, so I just end up simulating another Ctrl-Enter on the textbox, which has no effect.

Any help would be appreciated.


Solution

  • This is how I finally simulated an "Enter" on the textbox, even when the Ctrl key is down:

    var caretIndex = MyTextBox.CaretIndex;
    MyTextBox.Text = MyTextBox.Text.Insert(caretIndex, System.Environment.NewLine);
    MyTextBox.CaretIndex = caretIndex + 1;