Tuesday, August 20, 2013

C# Capturing Keys - KeyPress Event, KeyDown Event or KeyUp Event

Differences of the three:
  1. Keydown: happens when the key is pressed.
  2. KeyPressed: happens when a key is pressed and then released.
  3. KeyUp: happens when the key is released.

Sample Code below :-

1.Create a Textbox control.

2.Adding event to your control in form1.designer.cs
 
this.textbox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CaptureKeyPress);
this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(CaptureKeyDown);
this.textbox1.KeyUp += new System.Windows.Forms.KeyEventHandler(CaptureKeyUp);
3.Creating event handler
 
private void CaptureKeyPress(object sender, KeyPressEventArgs e)
{
    //key press capture key char
    //you can compare with keycode also
    if (e.KeyChar == (char)Keys.Enter)
    {
        MessageBox.Show("Enter Key Press");
    }
    //or can compare with ascii code
    if (e.KeyChar == 13) //13 in ascii code for enter
    {
        MessageBox.Show("Enter Key Press");
    }
}

private void CaptureKeyDown(object sender, KeyEventArgs e)
{
    //key down capture key code
    if (e.KeyCode == Keys.Enter) 
    {
        MessageBox.Show("Enter Key Down");
    }
}

private void CaptureKeyUp(object sender, KeyEventArgs e)
{
    //key up capture key code
    if (e.KeyCode == Keys.Enter) 
    {
        MessageBox.Show("Enter Key Up");
    }
}
get list of key char from ascii table.. link below..
get list of key code from keys enum.. link below..

Additional Reading at :
  1. ASCII Table
  2. List Keys Enumeration
  3. MSDN KeyPress
  4. MSDN KeyDown
  5. MSDN KeyUp