Closing form with escape key?

ThienZ

Freshman
Joined
Feb 10, 2005
Messages
45
Location
Germany
Is there any better way to close a form with escape key than making a button "Close", setting it as CancelButton, and then write inside a code to close like this :
Code:
private void buttonClose_Click(object sender, System.EventArgs e)
{
	this.Close();
}
?

thx in advance :)
 
Sure there is... :p
You have a solution that even works with no button.

Every Form have a property called: KeyPreview.
Setting this to TRUE will cause the Form to grab every imput from the user before it's processed to the actual control. This means that, even if the focus is on a TextBox, the KeyPress Event of the parent form will raise before the TextBox's do.

So, on the KeyPress Event of the Form, just validate if the Key is ESCAPE, if so, close it! :)

Alex :p
 
wow.. thx AlexCode... that's even better! Usually i make an extra button and set the width to 0 :lol:

Am i writing this right? cause this isn't working ^^;;; (I'm new to C# so i still need to get used to it...)
Code:
private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
	if(e.Equals(Keys.Escape))
		this.Close();
}
 
ThienZ said:
wow.. thx AlexCode... that's even better! Usually i make an extra button and set the width to 0 :lol:

Am i writing this right? cause this isn't working ^^;;; (I'm new to C# so i still need to get used to it...)
Code:
private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
	if(e.Equals(Keys.Escape))
		this.Close();
}

This will do, use the KeyDown event instead:
C#:
        Private Void Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        {
            If e.KeyValue = Keys.Escape Then this.Close();
        }
 
thx Alex, i tried to write like you did, but it didn't work... after some tries this code worked :
Code:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
	if((Keys) e.KeyValue == Keys.Escape) 
		this.Close();
}

Should i cast the int into Keys or are there better ways? Because .net can't compare int and keys...

thx :)

ps: how do make a quote with "C# Code"? i tried [C# Code][/[C# Code]] but it won't do :p
 
Sorry for the bad translation, I was writing it from VB.
And yeah, you must cast, specially because you seem to have Option Strict set to TRUE... right?

Alex :p
 
no problem Alex :)

i don't know about Option Strict, maybe it's an Option in VB? I guess this option is set to TRUE by default in C#...
 
C#:
i think it's [ cs ]

Option strict is something you turn on at the top of your code you can type Option Strict on, or true I don't know for c#. It makes the compiler stricter, but it results in faster programs.
 
Back
Top