Search code examples
c#winformscomboboxdebouncing

How can I debounce a C# Windows Forms ComboBox.PreviewKeyDown event?


I want to debounce a Windows Forms ComboBox.PreviewKeyDown event because it seems to always fire duplicate events. I would prefer only 1 event per keystroke.

For example:

  1. Create a new C# Windows Forms application (I tried .NET 4.6.2 and 4.7.2)

  2. Add a ComboBox and a TextBox to the main Form

  3. Set the textBox1.Multiline = true;

  4. Add the comboBox1.PreviewKeyDown event handler code to append results to the textBox1.Text

  5. Run and observe every keystroke in the comboBox1 fires the PreviewKeyDown event 2 times!

using System.Windows.Forms;

namespace ComboBox_Bounce
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      // Hookup event here in code, not in the Designer
      this.comboBox1.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.comboBox1_PreviewKeyDown);
    }

    private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
      this.textBox1.Text += "comboBox1_PreviewKeyDown=" + e.KeyCode.ToString() +  + System.Environment.NewLine;
    }
  }
}

enter image description here

Platform: Visual Studio 16.5.4, Windows 10 [1809] all current updates.


Solution

  • The Control.PreviewKeyDown should only be used for testing for a particular key press and then to set the Control.IsInputKey to true if that is the case, otherwise you should use the Control.KeyDown event handler.

    See Control.PreviewKeyDown Event