views:

399

answers:

3

As i understand it, when a keyboard button is pressed it should invoke the KeyDown event for the control which has focus. Then, the KeyDown for the parent control, so on and so forth until it reaches main form. UNLESS - along the chain one of the EventHandlers did:

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

In my case, KeyDown events never get to the main form. I have Form -> Panel -> button for example.

Panel doesn't offer a KeyDown Event, but it shouldn't stop it from reaching the main form right?

Right now as a work around I set every single control to call an event handler I wrote. I'm basically trying to prevent Alt-F4 from closing the application and instead minimize it.

+2  A: 

[Edit]

If you want to trap Alt-F4 then there's no point trying at the control level as that keystroke is handled by the application - see http://stackoverflow.com/questions/14943/how-to-disable-alt-f4-closing-form

Stuart Dunkeld
I tried that and it didn't work it's way up the chain either, same with KeyPress.
blak3r
A: 

Try creating an observer to capture your events:

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

Serge
+2  A: 

You can use an application 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
}
Simon Chadwick