Click here to Skip to main content
15,883,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys

I have found a way to handle individual key press on textboxes but this way I have to code each textbox on its own.
I would like to know how to set a rule / Key Press event for all textboxes on the form.
So when the Key: “ ‘ “ is pressed do nothing.
Im getting errors when saving data using the character “ ‘ “
I hope this makes sense... : )
Posted

Ami I got it to work:

set the KeyPreview property of the form to true

My Code..

VB
Sub Form1_KeyPress(ByVal sender As Object, _
    ByVal e As KeyPressEventArgs) Handles Me.KeyPress

    If e.KeyChar = ChrW(39) Then
        MessageBox.Show(("Form.KeyPress: '" + _
            e.KeyChar.ToString() + "' pressed."))

        Select Case e.KeyChar
            Case ChrW(39)
                MessageBox.Show(("Form.KeyPress: '" + _
                    e.KeyChar.ToString() + "' consumed."))
                e.Handled = True
        End Select
    End If
End Sub


End If
End Sub

End If
End Sub



Thank you so much for the help

Cheers
 
Share this answer
 
You can handle a Form event KeyPress[^] at the Form Level.
VB
Sub Form1_KeyPress(ByVal sender As Object, _
    ByVal e As KeyPressEventArgs) Handles Me.KeyPress

    If e.KeyChar >= ChrW(48) And e.KeyChar <= ChrW(57) Then
        MessageBox.Show(("Form.KeyPress: '" + _
            e.KeyChar.ToString() + "' pressed."))

        Select Case e.KeyChar
            Case ChrW(49), ChrW(52), ChrW(55)
                MessageBox.Show(("Form.KeyPress: '" + _
                    e.KeyChar.ToString() + "' consumed."))
                e.Handled = True 
        End Select 
    End If 
End Sub

This answer is just a reference of How to: Handle Keyboard Input at the Form Level[^]


Hope it helps.!
--Amit
 
Share this answer
 
v2
Comments
m@r10 24-Sep-12 1:52am    
Thank you very much Amit.
Have you got any code in VB.NET
Very new at this.
_Amy 24-Sep-12 2:13am    
I converted the code to VB.
m@r10 24-Sep-12 3:05am    
The VB code above does not work for the entire form. Handles Me.KeyPress if i change the Me to textbox1 it works.... any other suggestions. I need this to work for all textboxes on the form
m@r10 24-Sep-12 3:05am    
I have 60 textboxes on the form :(
Joan M 24-Sep-12 1:52am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900