I'm working through a book and my code is exactly the same as the book but not working correctly. Basically it's a typing game. System adds letters to a listbox which should disappear when I type them. Instead they're highlighting as I type them but are not being removed. I've even copied and pasted the code from the book website (headfirst c#) and it's still misbehaving! I suspect it's to do with a property setting for the timer or form or something?
Anyway here's the code:Form code:

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 Ch4_TypingGame
{
    public partial class Form1 : Form
    {
        Random random = new Random();
        Stats stats = new Stats();
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // Add a random key to the ListBox
            listBox1.Items.Add((Keys)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 the user pressed a key that's in the ListBox, remove it
            // and then make the game a little faster
            if (listBox1.Items.Contains(e.KeyCode))
            {
                listBox1.Items.Remove(e.KeyCode);
                listBox1.Refresh();
                if (timer1.Interval > 400)
                    timer1.Interval -= 10;
                if (timer1.Interval > 250)
                    timer1.Interval -= 7;
                if (timer1.Interval > 100)
                    timer1.Interval -= 2;
                difficultyProgressBar.Value = 800 - timer1.Interval;

                // The user pressed a correct key, so update the Stats object
                // by calling its Update() method with the argument true
                stats.Update(true);
            }
            else
            {
                // The user pressed an incorrect key, so update the Stats object
                // by calling its Update() method with the argument false
                stats.Update(false);
            }

            // Update the labels on the StatusStrip
            correctLabel.Text = "Correct: " + stats.Correct;
            missedLabel.Text = "Missed: " + stats.Missed;
            totalLabel.Text = "Total: " + stats.Total;
            accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
        }
    }
}

Stats class code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ch4_TypingGame
{
    class Stats
    {
        public int Total = 0;
        public int Missed = 0;
        public int Correct = 0;
        public int Accuracy = 0;

        public void Update(bool correctKey)
        {
            Total++;
            if (!correctKey)
            {
                Missed++;
            }
            else
            {
                Correct++;
            }
            Accuracy = 100 * Correct / (Missed + Correct);
        }

    }
}

Dani AI

Generated

Short summary: the symptom (letters being highlighted in the ListBox but not removed) means the ListBox is getting the keystrokes instead of the form. As noted, letting the form see key events first fixed it for . For anyone who still sees the problem (for example ), the cause is usually one of the following — verify these in order.

  • Confirm the form actually has the KeyDown handler wired (check the Events pane in the designer). Hooking in code looks like this.KeyDown += Form1_KeyDown; — if the handler is not attached the form never runs the removal logic.
  • Make sure the types in the ListBox match what you test/remove. If you add strings (e.g. "A") then Remove(e.KeyCode) will not match. Either add Keys values and remove e.KeyCode, or add strings and remove e.KeyCode.ToString().
  • Prevent the ListBox from doing its own selection after the form handles the key by suppressing the keypress: after removing the item set e.SuppressKeyPress = true; in the KeyDown handler so the control does not process the keystroke.
  • Confirm the timer is a Windows Forms timer (Tick runs on the UI thread). If a background timer is used, collection changes must be marshalled to the UI thread.
  • Debug: put a breakpoint inside the KeyDown handler and inspect listBox1.Items (type and ToString()), or log e.KeyCode to confirm the handler executes when a key is pressed.

If those checks fail, handle the ListBox's PreviewKeyDown or override ProcessCmdKey to capture keys earlier. These steps cover the common edge cases beyond the KeyPreview tip.

Recommended Answers

All 4 Replies

If the items in the list box get hightlight when you hit the keys this sounds like that form isn't getting your keydowns, but the listbox is because its focused. In the designer, click on the form's title bar to select it, then in the property inspector set the form's "KeyPreview" property to true. This will make the parent form get the key event instead of just the selected control in this case the listbox.

That should do it.

commented: Nice one +6

Thank you so much this was driving me nuts!
:)

Hi,

I also tried the same code and I am facing the same issue..."KeyPreview" set to true in my case by default. Still its not working the way it should.

Hi,

I also tried the same code and I am facing the same issue..."KeyPreview" set to true in my case by default. Still its not working the way it should.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.