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:
Create a new C# Windows Forms application (I tried .NET 4.6.2 and 4.7.2)
Add a ComboBox and a TextBox to the main Form
Set the textBox1.Multiline = true;
Add the comboBox1.PreviewKeyDown event handler code to append results to the textBox1.Text
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;
}
}
}
Platform: Visual Studio 16.5.4, Windows 10 [1809] all current updates.
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.