Displays a key pressed by the user : Key Event « Event « C# / C Sharp






Displays a key pressed by the user

Displays a key pressed by the user
using System.Drawing;
using System;

using System.Windows.Forms;

public class TryKey : Form {
  private char theKey = 'd'; 

  public TryKey() {
    Size = new Size(300,200);
    BackColor = Color.White;
  }
  protected override void OnPaint(PaintEventArgs e) {
    Graphics g = e.Graphics;                                                                  
    g.DrawString(theKey.ToString(), new Font("Arial", 36, FontStyle.Bold), Brushes.Red, 100, 50);
    base.OnPaint(e); 
  }
  protected override void OnKeyDown(KeyEventArgs e){
    if (e.Control){
       Console.WriteLine("Control");
    }
    if (e.KeyCode == Keys.Right){
       Console.WriteLine("Right");
    }
    else if (e.KeyCode == Keys.Left){
       Console.WriteLine("Left");
    }
    Invalidate(); 
    base.OnKeyDown(e);  
  }
  protected override void OnKeyUp(KeyEventArgs e) { 
    Console.WriteLine("Key Up");
    base.OnKeyUp(e);
  }
  protected override void OnKeyPress(KeyPressEventArgs e) {
    if (char.IsLetterOrDigit(e.KeyChar)){
      theKey = e.KeyChar;
    }  
    Invalidate(); 
    base.OnKeyPress(e);
  }
  public static void Main() {
    Application.Run(new TryKey());
  }
}

           
       








Related examples in the same category

1.Event system explained in detail
2.Close Form with Pressing X key
3.Check KeyCode from KeyEventArgs
4.Shift key pressedShift key pressed
5.Control Key pressedControl Key pressed
6.Alt key pressedAlt key pressed
7.Get Async Key StateGet Async Key State
8.Get Key action informationGet Key action information
9.Displaying information about the key the user pressedDisplaying information about the key the user pressed
10.Full screen and KeyEvent and MouseEvent
11.Key PressKey Press
12.Key Timer Key Timer
13.Keyboard SampleKeyboard Sample