3

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.

Community
  • 1
  • 1
Odsh
  • 697
  • 5
  • 20

2 Answers2

4

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;
Odsh
  • 697
  • 5
  • 20
  • 2
    For anyone following along, as a general best practice `System.Environment.NewLine` should be used instead of `\r`, `\n`, or `\r\n` – tehDorf Dec 15 '16 at 21:19
1

If you want to REALLY simulate some keypress, not just copy it's functionality, you should use InputSimulator, it's a great opensource library. Simulating a Ctrl+Enter would look like:

InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.RETURN);