Supressing keyboard events doesn't work

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I tried suppressing up/down arrow in a textbox. By default up/down
moves the cursor in the textbox left/right and I wanted to suppress
this default behavior in order to use the up/down keys for my own
purposes:


text.KeyDown += textBoxKeyDownHandler;

.....

private void textBoxKeyDownHandler(object sender,
System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Up)
e.SuppressKeyPress = true;
}


This didn't work. My handler is called, but the up/down keys work in
the textbox as before, they move the cursor left/right. Any tip what
I'm doing wrong?
 
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Up)

Of course, that's a typo and I used || instead of &&:

if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)

so that is not the problem.
 
Of course, that's a typo and I used || instead of &&:

if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)

so that is not the problem.

I even tried

private void textBoxKeyDownHandler(object sender,
System.Windows.Forms.KeyEventArgs e)
{
e.SuppressKeyPress = true;
Console.WriteLine(e.KeyCode);
}

but that doesn't work either! Every key in the textbox works normally
and the characters are printed to the console during typing. What am I
missing?
 
me.KeyPreview=False

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then e.Handled = True

If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then e.SuppressKeyPress =
True

End Sub



try following see if it helps..
 
Jared said:
me.KeyPreview=False

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then e.Handled = True

If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then e.SuppressKeyPress =
True

I tried this too, but it didn't help. According to the documentation
"Setting SuppressKeyPress to true also sets Handled to true.", so it's
not necessary anyway.
 
I tried setting this too. No effect.


I managed to do it by setting KeyPreview to true on the form and there
setting SuppressKeyPress to true. This way the textbox doesn't receive
the key.

It's still not clear, though. The documentation doesn't state I have to
catch key events on the form level in order to surpess them on an
individual control. Of course, it doesn't state the opposite either.

Nevertheless, it would be more natural to surpress key events on the
control level. Currently, if I want to suppress a certain key on a
certain control only then I have to catch the key event on the form
level and before suppressing it I have to check which control has the
focus. It would be much more intuitive to do the suppressing in the
individal control's KeyDown event.
 
Back
Top