Hmm, there is no reason to deny the Enter key when handling KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the text field control to False. This will prevent the multiline text field from responding to the Enter key.
Of course, this does not solve the Ctrl + Enter problem. Actually, the expected way to create a new line is when the AcceptsReturn property AcceptsReturn set to False. To solve this problem, you will need to handle one of the keyboard events and not allow the control to receive this input.
KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. This will catch them no matter what other modifier key they can be combined. Then, as soon as you find Enter, you want to set the e.Handled property to True so that it is not passed to the control.
But, unfortunately, we have not quite done it yet. The text box control tries to process certain keys inside, and you cannot override this in the key event handler method. You also need to tell the control not to interpret this particular key as an input key. There are two main ways to do this. The first (and recommended way) is to inherit the TextBox base class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is to handle the PreviewKeyDown event and set the IsInputKey property to False.
Code example:
private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
And, although I assume this is for testing purposes only, you definitely want to accept the MessageBox call from here for production code. Find another way to warn the user that their input was not allowed, for example, a short beep and the ErrorProvider component located next to the text box. The display of the message box is very sharp and not very user friendly. See my answer here for other tips and tricks.
source share