Blocking Unwanted Keystrokes in KeyPress Event

P

Phil Galey

In VB6 you can block invalid keystrokes in the KeyPress event by setting
KeyAscii = 0.

How can you block invalid keystrokes in VB.NET?
 
I

Imran Koradia

Override the ProcessCmdKey function on the form as below:

Protected Overrides Function ProcessCmdKey(ByRef msg As
System.Windows.Forms.Message, _
ByVal keyData As System.Windows.Forms.Keys) As Boolean
Select Case CType(msg.WParam.ToInt32, Keys)
Case Keys.Enter
MsgBox("enter")
Return True
Case Keys.Back
MsgBox("Backspace")
Return True
Case Else
Return MyBase.ProcessCmdKey(msg, keyData)
End Select
End Function

the "Return True" indicates you've processed that key and don't want the
base class (the form) to process it.
This way you can block virtually any type of key stroke (well, atleast those
that are defined in the 'Keys' enum).

hope this helps..
Imran.
 
I

Imran Koradia

Override the ProcessCmdKey function on the form as below:

Protected Overrides Function ProcessCmdKey(ByRef msg As
System.Windows.Forms.Message, _
ByVal keyData As System.Windows.Forms.Keys) As Boolean
Select Case CType(msg.WParam.ToInt32, Keys)
Case Keys.Enter
MsgBox("enter")
Return True
Case Keys.Back
MsgBox("Backspace")
Return True
Case Else
Return MyBase.ProcessCmdKey(msg, keyData)
End Select
End Function

the "Return True" indicates you've processed that key and don't want the
base class (the form) to process it.
This way you can block virtually any type of key stroke (well, atleast those
that are defined in the 'Keys' enum).

hope this helps..
Imran.
 
S

Shiva

Hi,
Handle the KeyPress event of the text box: Check the
KeyPressEventArgs.KeyChar and if it is something you want to block, set the
KeyPressEventArgs.Handled to True.

In VB6 you can block invalid keystrokes in the KeyPress event by setting
KeyAscii = 0.

How can you block invalid keystrokes in VB.NET?
 

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

Similar Threads


Top