Close Form

usvpn

Freshman
Joined
Apr 19, 2010
Messages
45
Edit by mod: thread is cross posted at XVBT.

Hi,
How can I close the form by pressing the scape button?
I know I can put a button on form and set the form CancelButton to this button, but is there another way without placing that button?
Thanks
 
Last edited by a moderator:
Atma's solution should work, but this might also be the rare case where the appropriate solution is to override the ProcessCmdKey function. If you want escape to close the form any time the user presses escape, even if it overrides another control's behavior for that key, then this would be an acceptable approach.

ProcessCmdKey is there to allow controls to implement accelerators or menu short-cuts.
MSDN said:
This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators and menu shortcuts.
Pressing escape to close a form falls close enough to this category, IMO. (Just realize that accelerators and menu short-cuts are the only reason you should override this method, and only when there is not a more straightforward solution.)
Visual Basic:
Public Class Form1
    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean

        If keyData = Keys.Escape Then Close()
        Return MyBase.ProcessCmdKey(msg, keyData)

    End Function
End Class
 
Back
Top