views:

233

answers:

3

We have a multi-line control that we are attempting to prevent the Enter/Return key from being used to create a new line.

Strangely enough, "AcceptsReturn" as False does not prevent this.

So we added the following:

Private Sub txtAddr_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAddr.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(13) Then
        e.Handled = True
    End If
End Sub

This works fine, however one of the QA people discovered hitting Control + Enter still puts in a newline.

How would we prevent this?

And why does AcceptsReturn being False not work as it appears it should? What is the intended purpose of it?

+1  A: 

Ctrl + enter is most likely to produce a line feed (ASCII 10).

It may depend on the specific system though.

If you are checking for carriage return (ASCII 13) and line feed though you probably have most bases covered.

Simon P Stevens
A: 

I'm guessing you'd have to trap this in the KeyDown, rather than the KeyPress event.

overslacked
+2  A: 

The AcceptsReturn property does something else. The Enter key normally operates the OK button on a dialog. With AcceptsReturn = true, the Enter key will enter a new line in the text box instead of activating the OK button Click event.

Pressing Ctrl+Enter will generate a line feed, TextBox treats this as a new line as well. Use this KeyDown event to filter all combinations:

private void textBox1_KeyDown(object sender, KeyEventArgs e) {
  if ((e.KeyData & Keys.KeyCode) == Keys.Enter) e.SuppressKeyPress = true;
}
Hans Passant