C #, WinForms: what would prevent KeyDown events from targeting to the main form? Only KeyDown leaf control works for me

As I understand it, when the keyboard button is pressed, it should raise the KeyDown event for the control with focus. Then KeyDown for the parent control, and so on and so on, until it reaches the main form. IF - down the chain, one of the EventHandlers did:

e.SuppressKeyPress = true;
e.Handled = true;

      

In my case, KeyDown events never hit the main form. For example, I have a form -> Panel ->.

The panel doesn't offer a KeyDown event, but shouldn't it prevent the main shape from reaching the correct way?

Now that I am working, I am setting up every single control to invoke the event handler that I have written. I mostly try to keep Alt-F4 from closing the application and minimizing it.

+2


a source to share


3 answers


[change]



If you want to catch Alt-F4, then there will be no point at the control level since this keypress is handled by the application - see How to disable the Alt + F4 close form?

+2


a source


You can use the app message filter:



using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.AddMessageFilter(new TestMessageFilter());
            Application.Run(new Form1());
        }
    }

    public class TestMessageFilter : IMessageFilter
    {
        private int WM_SYSKEYDOWN = 0x0104;
        private int F4 = 0x73;

        public bool PreFilterMessage(ref Message i_Message)
        {
            Console.WriteLine("Msg: {0} LParam: {1} WParam: {2}", i_Message.Msg, i_Message.LParam, i_Message.WParam);
            if (i_Message.Msg == WM_SYSKEYDOWN && i_Message.WParam == (IntPtr)F4)
                return (true); // Filter the message
            return (false);
        } // PreFilterMessage()

    } // class TestMessageFilter
}

      

+2


a source


Try creating an observer to capture your events:

http://ondotnet.com/pub/a/dotnet/2002/04/15/events.html

0


a source







All Articles