Today, I was trapped in an interesting issue while implementing a auto-complete URL dropdown in my new C# WinForm application. As in IE, I was able to select a url after it was visible in the dropdown but after selecting, enter press was just being ignored. (rather in IE, hitting enter enters the selected value in the box. I simply tried to implement KeyDown event for the ComboBox but to my despair, all the keys but "Enter" was being caught in the event by enter key wasn't invoking the event at all...
I went around Googling and it was not very late when I found the solution. and it was "Overriding IsInputKey method to have Enter key handled. here is the code..
public class YourComboBox : ComboBox
{
public YourComboBox() : base()
{
}
/// <summary>
/// Key Handler
/// </summary>
/// <param name="keyData"></param>
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Enter)
return true;
return base.IsInputKey (keyData);
}
}
Now your Combo box should be driven from YourComboBox and simply KeyDown event should be caught..(with little care)
private void yourComboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true; //remember this line to tell base function that you handled the event already...
//Do something...
}
}
This and you are all set...
Cheers!!