usvpn Posted September 29, 2010 Posted September 29, 2010 (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 September 30, 2010 by snarfblam Quote
Leaders snarfblam Posted September 30, 2010 Leaders Posted September 30, 2010 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 Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.