Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to detect when a user uses Tab key while with the KeyDown
event of the combobox. It seems to work fine with all the Keys (Enter,
T, ...) but not with the Tab key (e.KeyCode = Keys.Tab). Anyone
experienced similar problems? Any solutions, workarounds? thanks

Private Sub ComboBox1_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown


If e.KeyCode = Keys.Tab Then
Debug.WriteLine("hello") 'THIS NEVER PRINTS
End If

If e.KeyCode = Keys.Enter Then
Debug.WriteLine("hello") 'THIS PRINTS AS EXPECTED
End If
Posted

That's becuase the Tab is handled. Use the PreviewKeyDown event of the ComboBox and you'll get the press of Tab
 
Share this answer
 
v2
Comments
Abhinav S 25-Aug-11 8:25am    
We posted the same answer together. My 5.
Simon Bang Terkildsen 25-Aug-11 8:26am    
You posted a very good answer ;) +5
Abhinav S 25-Aug-11 8:28am    
Ha ha. :)
Use the OnPreviewKeyDown event[^] of the combobox.
 
Share this answer
 
The tab key is handled by the form itself, not the control. Why should the control care about the tab key? What I think you want to do is handle the LostFocus event. However, if you insist on trapping the tab key here's how to do it:

On MSDN [^]
 
Share this answer
 
v2
check the concept geven below Example...
public Form1()
{
InitializeComponent();

// Form that has a button on it
button1.PreviewKeyDown +=new PreviewKeyDownEventHandler(button1_PreviewKeyDown);
button1.KeyDown += new KeyEventHandler(button1_KeyDown);
button1.ContextMenuStrip = new ContextMenuStrip();
// Add items to ContextMenuStrip
button1.ContextMenuStrip.Items.Add("One");
button1.ContextMenuStrip.Items.Add("Two");
button1.ContextMenuStrip.Items.Add("Three");
}

// By default, KeyDown does not fire for the ARROW keys
void button1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
if (button1.ContextMenuStrip != null)
{
button1.ContextMenuStrip.Show(button1,
new Point(0, button1.Height), ToolStripDropDownDirection.BelowRight);
}
break;
}
}

// PreviewKeyDown is where you preview the key.
// Do not put any logic here, instead use the
// KeyDown event after setting IsInputKey to true.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900