开发者

Key pressed on form

开发者 https://www.devze.com 2023-01-20 18:43 出处:网络
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.

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!


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());

        }
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消