How to Trap Arrow/Direction Keys in a User Control

C

Charles Law

I'll kick myself when you tell me, but ...

I have a user control on a form, and I want the user control to see the
arrow keys when I press them. If I press just about any other key the
control's KeyDown event is fired, but not when I press a direction key.

I want to see them in the KeyDown event so that I can respond as soon as the
key is depressed, and I want to detect when the key is held down so that I
can perform an action repeatedly.

I am using VB.NET in Visual Studio 2005.

Please take pity on me.

TIA

Charles
 
J

Joergen Bech

Here is a snippet from one of my recent projets. Modify it to suit
your needs:

---snip---
Protected Overrides Function IsInputKey(ByVal keyData As
System.Windows.Forms.Keys) As Boolean
'Need to trap the following input combinations to prevent
the usercontrol
'from losing focus:

'1. Navigation keys alone
'2. Navigation keys + shift and/or ctrl

'Navigation keys are
'- arrow keys
'- home/end
'- page up/down

'Note: We do not process other editing keys (such as
Delete, copy, paste, etc)
' as these do not cause the control to lose focus.

Dim stdkeys As System.Windows.Forms.Keys = keyData And Not
Keys.Modifiers
Dim mods As System.Windows.Forms.Keys = keyData And
Keys.Modifiers

Dim shift As Boolean = ((mods And Keys.Shift) =
Keys.Shift)
Dim ctrl As Boolean = ((mods And Keys.Control) =
Keys.Control)

Dim shiftorctrl As Boolean = shift Or ctrl
Dim nomods As Boolean = (mods = Keys.None)

Dim navigationkeys As Boolean = (stdkeys = Keys.Left Or _
stdkeys = Keys.Up Or _
stdkeys = Keys.Right Or _
stdkeys = Keys.Down Or _
stdkeys = Keys.Home Or _
stdkeys = Keys.End Or _
stdkeys = Keys.PageUp Or
_
stdkeys = Keys.PageDown)

If (navigationkeys And nomods) Or _
(navigationkeys And shiftorctrl) Then

Return True

Else
Return MyBase.IsInputKey(keyData)

End If

End Function

---snip---

Regards,

Joergen Bech
 
C

Charles Law

Hi Joergen

Thanks for the reply. That is exactly what I needed; I didn't have to change
a line.

Many thanks.

Charles
 

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

Top