Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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

Edited by snarfblam
  • Leaders
Posted

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.

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.[/Quote] Pressing escape to close a form falls close enough to this category' date=' IMO. (Just realize that accelerators and menu short-cuts are the [i']only[/i] reason you should override this method, and only when there is not a more straightforward solution.)

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

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...