I am trying to get some keyboard response happening on a little test Windows Form Application, and I have a rough solution, which is to override ProcessCmdKey. However, there are several issues I am encountering, and inconsistencies I am finding.
Different Events: Is there a way to tell, in the arguments ref Message msg, Keys keyData, whether the even is a KeyDown, a KeyUp, or a KeyPress?
KeyPress: Everywhere I have looked says that KeyPress, ie a repeated keyboard input, only happens for character keys, which the arrow keys are not. However, the event handler is being called as frequently, and in the same mannor/with the same behaviour, for the arrow keys as character keys. Is this in face a KeyPress event, or is it something else?
I would ideally like a way to handle, at form level, all keyboard events without letting them get passed to the controls on the form. However, all the documentation sufficiently confused me, and missed key points, so that I have not been able to complete this.
Help on any of these topics is appreciated. Thanks!
The Message structure passed to ProcessCmdKey() contains the WINAPI message number in its Msg property:
WM_KEYDOWNis0x100(256),WM_KEYUPis0x101(257),WM_CHAR(roughly equivalent toKeyPress) is0x102(258),WM_SYSKEYDOWNis0x104(260),WM_SYSKEYUPis0x105(261).Concerning your question about
KeyPress, it is true that non-character keys such as the arrow keys do not generateWM_CHARmessages internally, but they do generateWM_KEYDOWN, and that message is also sent multiple times for repeated input.Also note that I’m not sure
ProcessCmdKey()is the right method to achieve what you want. The documentation describes it as only handlingmain menu command keys and MDI accelerators, which may only be a subset of the keys you want to catch. You might want to override ProcessKeyPreview() instead, which handles all the keyboard messages received by child controls.