I have a user control with several child controls. I need the user interface to react to keypresses, so I decided to put the handling code in a MainControl_KeyDown event. However, when I press a key in my application, this event does not fire.
I have found a solution through a search engine which relies upon use of the Windows API, which I would like to avoid, as it seems like overkill for what should be a function that is properly supported by the .NET framework.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With