As already pointed out in
Solution 1
by
OriginalGriff, showing a
MessageBox
every time a key is pressed makes it very difficult to type the text in
TextBox
. Instead create a
Label
and show the key pressed on that
Label
as shown below:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace KeyPressDisplayTextBox {
public partial class Form1 : Form {
private TextBox textBox1;
private Label label1;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
textBox1 = new TextBox();
textBox1.Location = new Point(10,10);
textBox1.KeyPress += textBox1_KeyPress;
Controls.Add(textBox1);
label1 = new Label();
label1.Location = new Point(10, 40);
label1.BorderStyle = BorderStyle.FixedSingle;
label1.Font = new Font("Arial", 14);
Controls.Add(label1);
}
void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
label1.Text = e.KeyChar.ToString();
}
}
}
To run the above code, create a
Windows Forms application
in
C#
with the name
KeyPressDisplayTextBox
, double click on
Form1
in the designer window which opens the code file, then replace the contents of
Form1.cs
with the above code and run the application.