Search code examples
c#keyboard-eventskeyeventargs

KeyEventArgs not responding to pressing escape button


I have a WinForm application in which i whish to use the escape button to close a control. I have created an event on KeyPress and this works when i use any other key than Escape.

private void ProductsView_KeyPress(object sender, KeyPressEventArgs e) 
{
    if (e.KeyChar == (char) Keys.B  || e.KeyChar == (char)Keys.Escape)
    {
        //Magic happens
    }
}

If i press 'b' everything works as expected, but if i press 'Escape', the event is not fired (yes, my escape button works). I have no clue what could cause this problem and i have also tried KeyUp & KeyDown events.


Solution

  • You can created nested control and override method ProcessCmdKey:

        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {
            switch (keyData)
            {
                case System.Windows.Forms.Keys.Escape:
                {
                    //...magic
                }
            }
        }