views:

26

answers:

3

Hi!

I have an windows forms application, with a form that holds 2 tabcontrols and a grid. I'd like to catch the pressing of esc key on any on this controls. The question is : is it a simpler way to do that without subscribing to the keypress event on each control ?

Thanks!

A: 

Subscribe to the event on the form itself.

If the control doesn't handle the event it should bubble up to the form where it will be handled.

ChrisF
This was the first thing i've tried, but apparently it doesn't bubble.
maephisto
@maephisto - have you turned PreviewKeyEvents (I think it's called that) on?
ChrisF
+1  A: 

You can Simply Do following. Implement an IMessageFilter and Handle Key Down event. Here is the complete Code to hook Escape Key Down.

public class MyKeboardHook:IMessageFilter
    {
        public const int WM_KEYDOWN = 0x0100;
        public const int VK_ESCAPE = 0x1B;
        public event EventHandler EscapeKeyDown;
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN && m.WParam == new IntPtr(VK_ESCAPE))
            {
                OnEscapeKeyPressed();
            }
            return false; //Do not Process anything
        }
        protected virtual void OnEscapeKeyDown()
        {
            if(this.EscapeKeyDown!=null)
            {
                EscapeKeyDown(this, EventArgs.Empty);
            }
        }
    }

Now you need to register this. The best place would be in Main

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MyKeboardHook myKeboardHook = new MyKeboardHook();
            myKeboardHook.EscapeKeyDown += (e, x) =>
                                                  {
                                                      MessageBox.Show("Escape Key Pressed");
                                                  };
            Application.AddMessageFilter(myKeboardHook);


            Application.Run(new Form1());

        }
    }
Int3
+1  A: 

This is what I was looking for. Thanks to Int3.

codebuilder
thanks I could be of your help.
Int3