Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# winform press any key

Posted on 2011-02-22
5
Medium Priority
?
1,397 Views
Last Modified: 2013-12-17
Hi,

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

Thanks,
JT
0
Comment
Question by:jtran007
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
ID: 34953572
Have you tried handling the KeyPress event?

private void Form1_KeyPress(object sender, KeyPressEventArgs e) {
      // Do stuff here
    }
0
 
LVL 9

Accepted Solution

by:
rawinnlnx9 earned 1000 total points
ID: 34953619
MSDN has a good discussion on this and below is a code excerpt. URL: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.71).aspx


// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

Open in new window



This discussion was also informative and showed a different way to approach things:

http://bytes.com/topic/c-sharp/answers/791541-traping-all-combinations-keypress-overriding-processcmdkey
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34954095
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();".
0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 34954128
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();
        }
0
 

Author Closing Comment

by:jtran007
ID: 34966666
Thanks,
JT
0

Featured Post

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question