Custom Keyboard navigation in UserControl hierarchy

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

Hi,

I am trying to implement some custom handling of the up/down arrow keys in a
parent UserControl with a collection of other Controls as children. The aim
being to move focus between the child controls vertically as well as
horizontally (horizontal navigation works fine out of the box)

I have spent hours trying various things in the debugger and viewing events
using "ControlInspector". I have reached the conclusion that these keys are
being handled somewhere "behind the scenes" in the "Message preprocessing"?
I can't find any articles on how this works or how to intercept these key
down events. Neither the parent control or the child controls see a Key Down
event and the Control.ProcessKeyPreview method in the parent does get the
Key Down message but after the default handling of the key has occurred!

I think the solution maybe something to do with the Control.IsInputKey() or
Control.ProcessKeyMessage() methods... am I on the right track?

Any help greatly appreciated.

tia
Chris
 
Well, in case anyone is interested I have solved the problem (by research
and trial and error)

In the derived child control insert the following to indicate that we want
to handle these keys.....

protected override bool IsInputKey(Keys key)
{
switch(key)
{
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Left:
return true;
}
return base.IsInputKey(key);
}

In the parent ContainerControl add an event handler for the KeyDown event in
the child control. You will now get the key down events for the indicated
keys and can customise the keyboard navigation (focus management) in the
parent whilst still retaining the AutoScroll functionality of the
ContainerControl.

child.KeyDown += new KeyEventHandler(parent.keyEventHandler)

The behind the scenes key event handling is still rather opaque to me but
the above seems to be a reasonably acceptable solution albeit increasing the
coupling between child and parent.

Chris
 
Back
Top