Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

KeyPress event - escape

Status
Not open for further replies.

PIAS

Programmer
Nov 2, 2005
38
0
0
SI
Hi!

I have two buttons on the form.
How can i make that when i press Key Escape, that form closes?

I was tryng with forms KeyPress event but it doesn't work. Why?
 
If one of the two buttons is the close or cancel button, you can set the CancelButton property of the form to that button and it will handle it for you.

Regards, Ruffnekk
---
Is it my imagination or do buffalo wings taste just like chicken?
 
set the CancelButton property of the form to one of the buttons.

in the _Click event of that button, enter the following code:

Code:
this.Close()


mr s. <;)

 
OK!

But what about if i dont want to set CancelButton properti?

I want to do so if i don't press any button but if i open form and press key ESC it closes form.

I did it now like this that i put this code


if (e.KeyChar == (char)27)
{
this.Close();
}

on both buttons and form and it woks, but is not elegant solution.

Is there any way to do it so that i put this code just on form?


Thanks!

PIAS
 
this.Close() would only be neccesary if the form is the startup form for the solution. If the form was shown by calling .ShowDialog() then you can omit that part.

Regards, Ruffnekk
---
Is it my imagination or do buffalo wings taste just like chicken?
 
the CancelButton property makes c# act as if the button has been clicked when the user presses the escape key.

imho a dialog should always have a Cancel button.

and, for the sake of consistency, a Cancel button and pressing the escape key should do the same thing.

if you don't want a Cancel button on the form, ask yourself what users who don't know that pressing Escape cancels dialogs will do. for certain they'll go to task manager and kill the process. *shudder*.


mr s. <;)

 
I know you should have a Cancel button, I agree, but you don't have to write any code for the button.. that's what I was trying to say ;)

Regards, Ruffnekk
---
Is it my imagination or do buffalo wings taste just like chicken?
 
sorry ruffnekk, i didn't mean to seem to contradict you, my post was aimed at the last one by PIAS.

why is it that setting CancelButton sets DialogResult, but AcceptButton doesn't?

*if a button has DialogResult set, and its parent form is shown using the ShowDialog() method, clicking it will close the form returning its DialogResult.


mr s. <;)

 
You'r right!

But this is just hipotetic question, if it can be done...

Thank you all for answers!

Bye!

PIAS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top