문제

I am trying to disable Mouse Scroll in my ToolStripComboBox, I thought I can catch the Mouse Wheel event, but while the event is available for ComboBox, it is not available instead for the ToolStripComboBox. Any ideas?

도움이 되었습니까?

해결책

The ToolStripComboBox helpfully exposes its underlying ComboBox control in its aptly named ComboBox property. This allows us to access its properties, methods, and events that were not been wrapped into the ToolStripComboBox.

And, as you probably know, the standard ComboBox control exposes a MouseWheel event that fires each time the mouse wheel is scrolled while the combo box has focus.

Putting these two things together, we can add a handler for the ToolStripComboBox control's underlying ComboBox control's MouseWheel event, and override its default behavior.

So, assuming you have a form that contains a ToolStrip and a ToolStripComboBox, you can use something like the following code:

public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();

      //Attach a handler for the MouseWheel event
      ToolStripComboBox1.ComboBox.MouseWheel += new MouseEventHandler(ToolStripComboBox_MouseWheel);
   }

   private void ToolStripComboBox_MouseWheel(object sender, MouseEventArgs e)
   {
      //Cast the MouseEventArgs to HandledMouseEventArgs
      HandledMouseEventArgs mwe = (HandledMouseEventArgs)e;

      //Indicate that this event was handled
      //(prevents the event from being sent to its parent control)
      mwe.Handled = true;
   }
}

Alternatively, of course, you could always subclass the existing ToolStripComboBox control and override its behavior there in the same way shown above.

다른 팁

In addition to what Cody Gray suggested you may want the wheel scolling to work when the combobox is dropped. Just chech the DroppedDown state in MouseWheel handle:


    public class MyToolStripComboBox : ToolStripComboBox
    {
        public MyToolStripComboBox()
        {
            this.ComboBox.MouseWheel += new MouseEventHandler(ComboBox_MouseWheel);
        }

        void ComboBox_MouseWheel(object sender, MouseEventArgs e)
        {
            if (!this.ComboBox.DroppedDown)
                ((HandledMouseEventArgs)e).Handled = true;
        }
    }

Scrolling dropped combobox with wheel doesn't change the selection, so it works as expected

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top