Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse events are not received by a WPF ScrollViewer when hosted in a WinForms container

We have a WinForms application that we are progressively converting to WPF. At this point the application's main form is a Form (WinForms) that contains a vertical sidebar built in WPF. The sidebar is hosted in an ElementHost control.

The sidebar is made of a ScrollViewer that contains other controls. The problem is that when the focus is somewhere in the WinForms aera and I use the mouse wheel over the ScrollViewer, it does not scroll.

This is related to the WPF/WinForms integration because in a 100% WPF project, the ScrollViewer reacts to the mouse wheel even if the focus is on another control.

What is the correct way to fix this?

like image 411
Sylvain Avatar asked Apr 19 '11 22:04

Sylvain


1 Answers

consider doing a message filter and when you receive WM_MOUSEWHEEL, determine if the mouse is over your WPF control. If so then send the message directly to your Element window handle.

Something like this:

System.Windows.Forms.Application.AddMessageFilter( new MouseWheelMessageFilter( YourElementInsideAnElementHost ) );

Dont forget to call RemoveMessageFilter when you go out of scope

public class MouseWheelMessageFilter : IMessageFilter
{
   private const int WM_MOUSEWHEEL = 0x020A;
   private FrameworkElement _element;

   [DllImport("user32.dll")]
   public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

   public MouseWheelMessageFilter(FrameworkElement element)
   {
       _element = element;
   }

   public bool PreFilterMessage(ref Message m)
   {
       if (m.Msg == WM_MOUSEWHEEL)
       {
           Rect rect = new Rect(0, 0, _element.ActualWidth, _element.ActualHeight);
           Point pt = Mouse.GetPosition(_element);

           if (rect.Contains(pt))
           {
               HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(_element);
               SendMessage(hwndSource.Handle, m.Msg, m.WParam, m.LParam);
               return true;
           }
       }

       return false;
   }
}
like image 160
Termit Avatar answered Sep 19 '22 00:09

Termit