'Why does my WPF application crash when I bump my mousewheel?

When I bump my mousewheel, my WPF application crashes sometimes, with an OverflowException. Here's the start of the stack trace:

at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest(WM uMsg, IntPtr wParam, IntPtr lParam, Boolean& handled)

From that, I've traced it down to the WindowChrome - I can even reproduce it with just the WindowChrome. But it seems like it has to be fullscreen. What's going on here? Is there a workaround?



Solution 1:[1]

The workaround that Ivan Golovi? included in a comment above needs to be in an answer so it can be spotted easily and in case the link goes dead.

Preprocess the message in a HookProc and mark it as handled if the conversion from lParam to int32 overflows.

protected override void OnSourceInitialized( EventArgs e )
  {
     base.OnSourceInitialized( e );
     ( (HwndSource)PresentationSource.FromVisual( this ) ).AddHook( HookProc );
  }
  private IntPtr HookProc( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled )
  {
     if ( msg == 0x0084 /*WM_NCHITTEST*/ )
     {
        // This prevents a crash in WindowChromeWorker._HandleNCHitTest
        try
        {
           lParam.ToInt32();
        }
        catch ( OverflowException )
        {
           handled = true;
        }
     }
     return IntPtr.Zero;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RobinG