Search code examples
textboxnewlinemultilineshiftenter

.NET Multiline Textbox Make Shift+Enter working instead of Enter key


I have a Windows Form Multiline Textbox. I want to use Shift+Enter Instead of using Enter key to make a new line in textbox, and the traditional Enter key will be used to focus on the next control. I mean Shift+Enter will work exactly like Enter key on normal multiline textbox (Regard to textbox maxlength --> So you cant enter newline, or current selected text will be delete when you insert newline,...)

I've tried to override OnKeyDown, to insert newline on Shift+Enter, but it doesn't work as I expected.


Solution

  • you'll need to override OnKeyDown and check for enter key using the KeyDownEvent's KeyCode property.

    If enter was pressed and the keydownevent's modifiers property does not equal Keys.Shift you'll need to suppress the key press. Here's the documentation on how to do that:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.suppresskeypress(v=vs.110).aspx

    If shift+enter was pressed you'll need to insert Environment.NewLine at the cursor position, then move the cursor after the inserted Environment.NewLine. Here's how to do that:

    How to paste text in textbox current cursor?