Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing KeyDown events in a UserControl

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.

like image 552
Mark Withers Avatar asked Jul 20 '09 10:07

Mark Withers


2 Answers

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);
   }
}
like image 91
Masoud Avatar answered Oct 11 '22 15:10

Masoud


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.

like image 20
Skalli Avatar answered Oct 11 '22 16:10

Skalli