qqqq1961
qqqq1961

Reputation: 95

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

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.

Upvotes: 0

Views: 497

Answers (1)

Victor
Victor

Reputation: 2371

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);
}

Upvotes: 1

Related Questions