Click here to Skip to main content
15,906,628 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have 2 controls in which I want to detect a key pressed.
At first I used
VB
Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
...
MyBase.OnKeyDown(e)
End Sub

but I discovered that the key pressed event was raised in the wrong control so I used
VB
Private Sub EditBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

End Sub

Thinking this would focus the keydown event, but it doesn't

Help??
Posted
Comments
Ankit Rajput 22-Apr-11 6:51am    
Your question is not clear.
Please ask clearly what you want to know?

1 solution

In the first piece of code you override OnKeyDown. This is done when you are a derived class and need to do something yourself when this event occurs.

In the second piece of code you handle the event with the EditBox_KeyDown. You need to make sure that you implement the event handler for each control.

If you want to get the keydown event for the overall form (no matter what control is focused), you set the KeyPreview of the Form to True and create a handler for the form keydown event. Have a look here for more info:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview%28v=vs.71%29.aspx[^]

Good luck!
 
Share this answer
 
Comments
Stuart Nathan 22-Apr-11 8:39am    
KeyPreview does not seem to apply to a control - only a form.
E.F. Nijboer 22-Apr-11 10:35am    
Yes, that is correct. But even if a control has focus, the keydown event of the form will fire before the that of the control. Maybe you could give some additional information because it might not be completely clear.
Stuart Nathan 22-Apr-11 11:05am    
I have had a look at the form on which these controls are placed and yes
KeyPreview=True
I have set it to false and debugging.
E.F. Nijboer 22-Apr-11 11:10am    
With KeyPreview=True the event of both the Form and the control should get raised unless the Form event is actively clearing the event.
Stuart Nathan 22-Apr-11 11:14am    
Actually one of the controls did raise the event, but not the other.
Still it seems to be working - so a big thankyou!

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