Click here to Skip to main content
15,885,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to develop C# skills coming from VB.Net extensive use
I would like a book recommendation for C# winforms and sqlite FREE would be nice

I am trying to close my application on the main form named frmStart
YES I have looked at the Related Entries one works but I do not understand the code. Not sure why I need to override and use a bool

I will post the three code samples I tested
Visual Studio 2019 ver 16.11.11 C# tool 3.11

What I have tried:

/*private void Form_KeyCode(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)

    {
        this.Close();
    }
    }*/


/*private void frmStart_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)27)
     Application.Exit();
}*/

// THIS Works but it looks messy
/*protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Escape)
    {
        this.Close();
        //Application.Exit();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}*/
Posted
Updated 18-Jan-23 0:10am

There are simpler ways:
If you have a Cancel button or similar, just set the Form.CancelButton property to that button, and the framework will do all the work for you.

If not, then set the Form.KeyPreview propperty to True, and add a KeyDown handler:
C#
private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}
That should work without needing to override anything.

The override of ProcessCmdKey allows you code to "chain" itself into the handler that detects system keys (like ENTER, TAB, ESC) that are always handled by the form instead of passed to the focussed input control instead.
 
Share this answer
 
Comments
Choroid 13-Jan-23 16:49pm    
Griff just tested the code NO RESULTS yes I have the KeyPreview set to True looked at the CancelButton but I did not want another button on the form Thank You for the override explanation all the answers I looked at I never saw code constructed for this task that way Live and Learn
OriginalGriff 14-Jan-23 4:31am    
There is a really simple, cheaty way to do it: add a button to your form, call it "CloseMe", set it's Size to (0,0), set it's Location to (0,0), set Tabstop to False, and handle it's Click event - all you need it to do is to call Close on the form.
Set the Form.CancelButton to CloseMe.
Now the system will close the form when you hit ESC, which closes the app, but the button is not seen or accessible.
BillWoodruff 19-Jan-23 6:48am    
excuse me for saying this is a trick/hack, it increases UI/code obscurity, and, i would never expose a student to a technique like this. curmudgeon bill :)
Choroid 14-Jan-23 10:56am    
Works like a charm! I guess years of programming you learn a few tricks along the way
How it works still a bit of a puzzle ? Time to do a little reading C# is NOT VB.Net
OriginalGriff 14-Jan-23 11:34am    
The difference between a Form and a Dialog is down to how you display them! A Form is really the same thing as a Dialog: and since you have Accept / OK and Cancel buttons on a Dialog you can also have them on a Form.

And on a Dialog you can normally close it and return OK by clicking the OK button or pressing ENTER - this is called an "Accept button". Equally, you can close the Dialog and return Cancel by clicking the Cancel button or pressing ESC - try it: it works in Load and Save dialogs for example.

So if you create a Cancel button in your form, whenever you press ESC the system will simulate a click and call the handler method.
So if you have a invisible Cancel button, the system doesn't care - it calls your handler and your form closes. If that's the startup form then that causes the whole app to close!

Easy really! :D
Another way:

1) set the Main Form 'KeyPreview property to 'true.

2) define a 'KeyDown event handler bound to the Main Form window:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}
But, should you do this ? This will close the app, and any other Forms you are displaying. It will not work in whatever shown modally that has focus.

It's not typical Windows app behavior, and may confuse others.

And, there are cases where you really should clean-up/dispose of certain objects you may have created. Give the app user a choice:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        if (MessageBox.Show("exit application?", "think about it !", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            // call your code to clean-up here
            Application.Exit();
        }
    }
}
 
Share this answer
 
Comments
Choroid 18-Jan-23 12:17pm    
Bill Thanks for the code Sorry to say I tried both options and NO RESULTS
the frmStart is the entry point for the C# application
This is a little more than a puzzle as I see your code posted as answers on a number of sites
Something is stopping the app from reading the keyboard
BillWoodruff 18-Jan-23 20:16pm    
Assuming this is a WinForms app created by using Visual Studio's 'New Project' menu:

Look at the program.cs file, and show the code that starts the APP.
If 'frmStart is the Main Form, the code I showed will work.
Choroid 18-Jan-23 22:11pm    
Bill I created a new application and tested your code
YES VS 2019 WinForms C# Net 4.8
I believe your code will work
namespace WFTest
{
static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmStart());
}
}
}
BillWoodruff 19-Jan-23 0:04am    
Well does it work or not ? Do you understand now why your original code does not work.

There is nothing about the technique that depends on FrameWork version.

Please express your judgement of solutions by accepting or voting, or both.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900