Capturing KeyDown events in a UserControl
You can add following method to your usercontrol
:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((keyData == Keys.Right) || (keyData == Keys.Left) ||
(keyData == Keys.Up) || (keyData == Keys.Down))
{
//Do custom stuff
//true if key was processed by control, false otherwise
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
I know this thread is a bit old, but I had a similar problem and handled it in a different way:
In the main-window I changed the KeyPreview attribute to true.
I registered the KeyDown-event handler of the main window in my user control.
this.Parent.KeyDown += new KeyEventHandler(MyControl_KeyDown);
This prevents me from routing the KeyDown event of every child control to my user control.
Of course it's important to remove the event handler when you unload your user control.
I hope this helps people who face a similar problem now.