How to catch an ESC KeyPress using WndProc?
Asked
Active
Viewed 9,140 times
2
-
I'm assuming that you mean while your form has focus, in which case I'd go with tommeib's solution. If not, you should provide more info. – snarf Mar 21 '10 at 14:01
-
This is not relevant for the OP, but for others who end up here the usual best way to handle Esc in a WinForms program is by overriding ProcessCmdKey. See the answer by Hans Passant on this thread: http://stackoverflow.com/questions/10468200/key-events-processcmdkey – RenniePet Aug 07 '14 at 12:29
4 Answers
5
Another option (for forms):
protected override bool ProcessKeyPreview(ref System.Windows.Forms.Message m)
{
int VK_ESCAPE = 27;
if (m.Msg == Win32Constants.WM_KEYDOWN && (int)m.WParam == VK_ESCAPE)
{
// ...
}
return base.ProcessKeyPreview(ref m);
}

adjutant
- 63
- 1
- 4
3
Why are you doing it this way? Why not set the PreviewKey
property of the Form to true
and set a global event handler for KeyUp
and check it...
if (e.KeyCode == Keys.Esc){ //... }

t0mm13b
- 34,087
- 8
- 78
- 110
-
1This won't work with certain keys, but it seems to work fine with the escape key. BTW, I believe it's KeyPreview. – snarf Mar 21 '10 at 14:00
-
0
(msg==WM_KEYDOWN) && (wParam==VK_ESCAPE) ... ops it was c#... sorry , that is win32 api way

Luca Rocchi
- 6,272
- 1
- 23
- 23