Link to home
Start Free TrialLog in
Avatar of jtran007
jtran007

asked on

C# winform press any key

Hi,

I  have a winform app, how can write code to handle any key press to exit my program?

Thanks,
JT
Avatar of ViceroyFizzlebottom
ViceroyFizzlebottom
Flag of United States of America image

Have you tried handling the KeyPress event?

private void Form1_KeyPress(object sender, KeyPressEventArgs e) {
      // Do stuff here
    }
ASKER CERTIFIED SOLUTION
Avatar of rawinnlnx9
rawinnlnx9
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike Tomlinson
You may need to set the Forms KeyPreview() Property to True to get the KeyPress() event to work properly (depends on which controls you have on your form).

To close the app, from the main form, use "this.Close();".
set form's KeyPreview property to true.

this.KeyPreview = true;

and handle any of these event

KeyDown(object sender, KeyEventArgs e)

KeyPress(object sender, KeyPressEventArgs e)

KeyUp(object sender, KeyEventArgs e)

like this :

 private void TestForm_KeyDown(object sender, KeyEventArgs e)
        {
            Application.Exit();
        }
Avatar of jtran007
jtran007

ASKER

Thanks,
JT