2

How to catch an ESC KeyPress using WndProc?

Braiam
  • 1
  • 11
  • 47
  • 78
Pritorian
  • 414
  • 8
  • 19
  • 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 Answers4

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
0

You need to catch the WM_CHAR message and check WParam.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

(msg==WM_KEYDOWN) && (wParam==VK_ESCAPE) ... ops it was c#... sorry , that is win32 api way

Luca Rocchi
  • 6,272
  • 1
  • 23
  • 23