Search code examples
c#winformsbitwise-operatorswndprocintptr

IntPtr.ToInt32 with Bitwise operator causes OverflowException on 64-bit process


I want to override some functionality in a control, by disabling zooming when the Ctrl button is clicked and the mousewheel is moved. This works fine on 32-bit processes but on 64-bit processes, I get an overflow by converting the IntPtr to an Int32. How can I rework this so that it works on both 32-bit and 64-bit processes? I can't use bitwise operators with IntPtrs.

Should my constants instead be set to long and then do IntPtr.ToInt64()? Would that work properly on both 32-bit and 64-bit processes? Anything I need to worry about if I make that change?

private const int WM_MOUSEWHEEL = 0x020A;
private const int MK_CONTROL = 0x0008;
//Prevent CTRL+Mouse Wheel from Zooming
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg == WM_MOUSEWHEEL)
    {
       if ((m.WParam.ToInt32() & MK_CONTROL) != 0)
       {
            // Ignore CTRL+WHEEL
            return;
       }
    }

    base.WndProc(ref m);
}

Solution

  • Use the existing .NET callbacks that already unwrap the parameters correctly. In WinForms there is the Control.OnMouseWheel method. The modifier keys are available via the ModifierKeys property.

    protected override void OnMouseWheel(MouseEventArgs m)
    {
        if ((ModifierKeys & Keys.Control) != 0)
        {
            ((HandledMouseEventArgs)m).Handled = true;
            // Ignore CTRL+WHEEL
            return;
        }
    
        base.OnMouseWheel(m);
    }