Search code examples
c#winformscomboboxarrow-keys

Jump ComboBox on Arrow key pressed


When i press UP/DOWN arrows on every control which have tabstop property set to true then PREVOIUS/NEXT tabindex is selected. It works fine but when ComboBox is focused it changes it's value cause it trapped arrow too.

How can i achieve tabindex jump without sending the keystroke to ComboBox?

Code which handles tabindex jumping:

private void ParentForm_KeyDown(object sender, KeyEventArgs e)
    { 
    Control ctl;
    ctl = (Control)sender;
    if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Enter)
    {
        ctl.SelectNextControl(ActiveControl, true, true, true, true);

    }
    else if (e.KeyCode == Keys.Up)
    {
        ctl.SelectNextControl(ActiveControl, false, true, true, true);

    }



}

Solution

  • You cannot do this with KeyPreview or the form's KeyDown event. That's VB6 legacy, navigation keys were intercepted before they fired KeyDown. You must override the form's ProcessCmdKey() method instead.

    It is in general quite ugly to solve a problem this way, it is a global solution to a localized problem. You'll break other controls when you do this, like RichTextBox or a multi-line TextBox for example, leaving your user utterly stumped why they misbehave. The much cleaner approach is to just create your own ComboBox control that doesn't swallow the cursor keys. Add a new class to your project and paste the code shown below. Compile. Drop your new control from the top of the toolbox, replacing the existing combo.

    using System;
    using System.Windows.Forms;
    
    class MyComboBox : ComboBox {
        protected override bool IsInputKey(Keys keyData) {
            if ((keyData == Keys.Up) || (keyData == Keys.Down)) return false;
            return base.IsInputKey(keyData);
        }
    }