keyPress event in C#



Windows Forms processes keyboard input by raising keyboard events in response to Windows messages. Most Windows Forms applications process keyboard input exclusively by handling the keyboard events.



How do I detect keys pressed in C#
You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:
                                                         
                              KeyDown
                                              KeyPress
                                              KeyUp


How to detect when the Enter Key Pressed in C#
The following C# code behind creates the KeyDown event handler. If the key that is pressed is the Enter key, a MessegeBox will displayed .
  if (e.KeyCode == Keys.Enter)
  {
            MessageBox.Show("Enter Key Pressed ");
  }





Example...................

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace keypressevents
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

      

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            int asc = (int)e.KeyChar;
            if (Char.IsDigit(e.KeyChar) == false && asc!=8)
            {
                e.Handled = true;

            }
        }

Comments