views:

522

answers:

3

Does anyone know of a way to disable the mouse scroll wheel when a control such as a combobox or listbox has focus? For my purposes, combobox is all I need the answer for.

I have a combobox set to trigger a SQL query on SelectedIndexChanged, and accidentally scrolling the wheel while the combobox has focus causes about six SQL queries to fire off simultaneously.

A: 

One such option would be to add a handler to the comboBox, and within that comboBox, resolve the situation. I'm not sure how your code is set up, but I'm assuming if you knew when the event was happening, you could set up some kind of conditional to prevent the queries from happening

 '''Insert this statement where your form loads
 AddHandler comboBoxBeingWatched.MouseWheel, AddressOf buttonHandler

 Private Sub buttonHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
     '''Code to stop the event from happening
 End Sub

In this way, you'd be able to maintain the user being able to scroll in the comboBox, but also be able to prevent the queries from happening

AndyPerfect
+1  A: 

If you subclass the control it's possible (apologies for the C#)

public class NoScrollCombo : ComboBox
{
    [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
    protected override void WndProc(ref Message m)
    {
        if (m.HWnd != this.Handle)
        {
            return;
        }

        if (m.Msg == 0x020A) // WM_MOUSEWHEEL
        {
           return;
        }

        base.WndProc(ref m);
    }
}
Stuart Dunkeld
+1  A: 

The ComboBox control doesn't let you easily override behavior of the MouseWheel event. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

Friend Class MyComboBox
    Inherits ComboBox

    Protected Overrides Sub OnMouseWheel(ByVal e As MouseEventArgs)
        Dim mwe As HandledMouseEventArgs = DirectCast(e, HandledMouseEventArgs)
        mwe.Handled = True
    End Sub
End Class

Beware that this also disables the wheel in the dropdown list.

Hans Passant
This works great. Thanks.
Caleb Thompson