Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Oct 6, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Enable a key-skipping mechanism for a TextBox

' Enable the key-skipping mechanism for the input TextBox and for the input 
' chars
' Example: don't process the 'A', 'b' and '0' chars
'   EnableTextBoxCharSkip(TextBox1, "A"c, "b"c, "0"c)

Sub EnableTextBoxCharSkip(ByVal tb As TextBox, ByVal ParamArray keysToSkip() As _
    ' save the array of keys textbox's Tag property
    tb.Tag = keysToSkip
    ' attach the txtbox's KeyPress event to the GenTextBox_KeyPress event 
    ' handler
    AddHandler tb.KeyPress, AddressOf GenTextBox_KeyPress
End Sub

' Disable the key-skipping mechanism for the input textbox
' Example: DisableTextBoxCharSkip(TextBox1)

Sub DisableTextBoxCharSkip(ByVal tb As TextBox)
    ' detach the textbox's KeyPress event from the GenTextBox_KeyPress event 
    ' handler
    RemoveHandler tb.KeyPress, AddressOf GenTextBox_KeyPress
    tb.Tag = Nothing
End Sub

' Handle the textbox's KeyPress event to skip the keys of the array stored in 
' the textbox's Tag property
Private Sub GenTextBox_KeyPress(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyPressEventArgs)
    ' cast the generic Object sender to a TextBox
    Dim tb As TextBox = DirectCast(sender, TextBox)
    ' cast the textbox's Tag to an array of Char, that contains the chars to 
    ' skip
    Dim keysToSkip() As Char = DirectCast(tb.Tag, Char())
    ' if the pressed key is found in the array of "bad" keys,
    '  overrides its default processing with "do nothing"
    If Array.IndexOf(keysToSkip, e.KeyChar) > -1 Then e.Handled = True
End Sub
Marco Bellinaso
Thanks for your registration, follow us on our social networks to keep up-to-date