TextBox controls support KeyDown, KeyPress, and KeyUp standard events. One thing that you will often do is prevent the user from entering invalid keys. A typical example of where this safeguard is needed is a numeric field, for which you need to filter out all nondigit keys:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Is < 32 ' Control keys are OK.
Case 48 To 57 ' This is a digit.
Case Else ' Reject any other key.
KeyAscii = 0
End Select
End Sub
You should never reject keys whose ANSI code is less than 32, a group that includes important keys such as Backspace, Escape, Tab, and Enter. Also note that a few control keys will make your TextBox beep if it doesn't know what to do with them—for example, a single-line TextBox control doesn't know what to do with an Enter key.
Don't assume that the KeyPress event will trap all control keys under all conditions. For example, the KeyPress event can process the Enter key only if there's no CommandButton control on the form whose Default property is set to True. If the form has a default push button, the effect of pressing the Enter key is clicking on that button. Similarly, no Escape key goes through this event if there's a Cancel button on the form. Finally, the Tab control key is trapped by a KeyPress event only if there isn't any other control on the form whose TabStop property is True.
You can use the KeyDown event procedure to allow users to increase and decrease the current value using Up and Down arrow keys, as you see here:
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyUp
Text1.Text = CDbl(Text1.Text) + 1
Case vbKeyDown
Text1.Text = CDbl(Text1.Text) -1
End Select
End Sub
There's a bug in the implementation of TextBox ready-only controls. When the Locked property is set to True, the Ctrl+C key combination doesn't correctly copy the selected text to the Clipboard, and you must manually implement this capability by writing code in the KeyPress event procedure
No comments:
Post a Comment
Comment will be published after moderation only. Do not advertise here.