Hi everyone, I'm trying to write this code. Whenever a user types a letter that matches what is already displayed, it should clean up the list box..the problem here is it is not detecting the keyDown event. What is wrong? Thanks for the help. Code: namespace TypingGame { public partial class Form1 : Form { Status status = new Status(); Random random = new Random(); public Form1() { InitializeComponent(); this.KeyDown +=new KeyEventHandler(Form1_KeyDown); } private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void timer1_Tick(object sender, EventArgs e) { listBox1.Items.Add((Keys) this.random.Next(65, 90)); if (listBox1.Items.Count > 7) { listBox1.Items.Clear(); listBox1.Items.Add("Game Over!"); timer1.Stop(); } } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (listBox1.Items.Contains(e.KeyCode)) { status.update(true); listBox1.Items.Remove(e.KeyCode); listBox1.Refresh(); } else status.update(false); this.CorrectLabel.Text = "Correct: " + status.Correct; this.missedLabel.Text = "Missed: " + status.Missed; this.accuracyLabel.Text = "Accuracy: " + status.Accuracy; } private void Form1_Load(object sender, EventArgs e) { timer1.Start(); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { } } }
Your Form1 only detects key events when it's focused, but that only happens when it contains no control. If it contains any control, the focus will be on one of these controls. So when pressing a key down, the focused control can detect that, the Form1 can't. But you can make it check all key events before other controls by setting Form1.KeyPreview = true; Thanks !
You've attached the keydown event to the form, is that what you wanted to do? If you are in the listbox when you press the key, it will handle the keypress and not pass it to the form...