Home > OS >  How to disable scrolling of comboBox from keys arrow Up\Down when it closed?
How to disable scrolling of comboBox from keys arrow Up\Down when it closed?

Time:05-15

The arrow keys should scroll only pictureBox (placed in panel). It works fine. But it also scroll through comboBox items though it is closed (droppedUp). How to disable it?

private void Form1_Load(object sender, EventArgs e)
{
     comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
     comboBox1.DroppedDown = false;
     comboBox1.Items.Add("111");
     comboBox1.Items.Add("222");
}
 
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Down)
    {
          Point current = panel1.AutoScrollPosition;
          Point scrolled = new Point(current.X, -current.Y   50);
          panel1.AutoScrollPosition = scrolled;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

I had read about Control.PreviewKeyDown event: preview key event and also found another example: preview key event but I cannot understand how it used in my case.

CodePudding user response:

As Hans Passant commented, you must return true. Also, add some other keys that maybe change the selected item in the combobox:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Down || 
        keyData == Keys.Up ||
        keyData == Keys.PageDown ||
        keyData == Keys.PageUp)
    {
        Point current = panel1.AutoScrollPosition;
        Point scrolled = new Point(current.X, -current.Y   50);
        panel1.AutoScrollPosition = scrolled;
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
  • Related