KeyDown not fired if Button on a Form !

J

jmd.msdn

Hello.
I want to trap the KeyDown key on a form.

What I do :
1. Create a Windows Forms C# Project
2. Add a KeyDown event for the form
Add a MessageBox.Show("KeyDown hitted"); in this event.
3. Run the program
With the above, each time I press a key, ANY key (also any of the arrow
keys), the MessageBox fire correctly.

Now the problem :
1. Add a Button on the form (with or without a Click event)
2. Run the program
This time, the form's KeyDown event is fired for keys, EXCEPT THE ARROW KEYS
!!!

Is this normal ?
What must I do to solve that ?

Thank you.
jean-marie
 
J

Jeffrey Tan[MSFT]

Hi jean,

Thanks for your post.

Yes, this behavior is by design. This is because .Net winform is built upon
the underlying window UI component. In Win32 SDK, the keyboard messages
will be sent to the focused window. So if there is a button control on the
form, all the keyboard messages will be sent to Button window's(yes, in
Win32 SDK, all controls are windows) procedure. Form's window procedure
will have no keyboard messages in this scenario, so the KeyDown event will
not fire at all.

To resolve this issue, .Net Winform provided an IMessageFilter interface,
which can define a filter for winform application. I have writen a sample
to demonstrate the usage, like this:

static void Main()
{
Application.AddMessageFilter(new TestMessageFilter());
Application.Run(new Form1());
}

public class TestMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
const int WM_KEYDOWN= 0x0100;
// Blocks all the messages relating to the left mouse button.
if (m.Msg==WM_KEYDOWN)
{
MessageBox.Show("KeyDown hitted");
}
return false;
}
}

This works well on my side. Hope it helps

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

jmd.msdn

Thank you very much.
It's ok now with your sample on PreFilterMessage.

Best regards.
jean-marie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top