Strange problem with the minus(subtract) key

R

roidy

I have a text box and I need to limit the input to just numbers, backspace
and the minus(subtract) key. I`ve set up a KeyPress event for the text box
and am using the following code:-

Private Sub textbox_KeyPress(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles textbox.KeyPress

If Not Char.IsNumber(e.KeyChar) And _
Not e.KeyChar = Chr(Keys.Back) And _
Not e.KeyChar = Chr(Keys.Subtract) Then
e.Handled = True
End If
End Sub

This works perfectly for the number keys and the backspace key but not for
the minus(subtract) key. I can replace Keys.Subtract for any other key on
the keyboard and it works but I can`t get Keys.Subtract to work. Any ideas?

Thanks
Rob
 
T

Teemu

This works perfectly for the number keys and the backspace key but not for
the minus(subtract) key. I can replace Keys.Subtract for any other key on
the keyboard and it works but I can`t get Keys.Subtract to work. Any
ideas?

Does this work as you expected:

If Not Char.IsNumber(e.KeyChar) AndAlso _
Not e.KeyChar = Chr(Keys.Back) AndAlso _
Not e.KeyChar = "-" Then
e.Handled = True
End If


-Teemu
 
R

roidy

That worked perfectly, it never occurred to me to just use "-", seems
strange that Keys.Subtract doesn't work through.

Thanks
Rob
 
T

Teemu

roidy said:
That worked perfectly, it never occurred to me to just use "-", seems
strange that Keys.Subtract doesn't work through.

I'm not totally sure, but if I remember correctly, these Keys.Subtract,
Keys.Add and others should be used only in KeyDown and KeyUp events to look
up e.KeyCode.

KeyPress event returns just a character and KeyUp and KeyDown events return
a key code for example F-buttons and other special buttons.

-Teemu
 
R

roidy

Yep I just tested it and your right, but it seems kind of strange that
Keys.Back and most other keys can be used in a KeyPress event but not
Keys.Subtract. Oh well.

Rob
 
T

Teemu

roidy said:
Yep I just tested it and your right, but it seems kind of strange that
Keys.Back and most other keys can be used in a KeyPress event but not
Keys.Subtract. Oh well.

Those Keys enumerations which have same integer as character's ASCII code
(letters, backspace and a few others) will "accidentally" work although it
is much easier to use for example "h" or "&" in KeyPress event.

-Teemu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top