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

自闭症网瘾萝莉.ら 提交于 2019-12-23 09:35:29

问题


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?


回答1:


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;
   }
}



回答2:


Try setting the focus to the ElementHost by calling elementHost.Select() This made the MouseWheel event work for me.



来源:https://stackoverflow.com/questions/5723290/mouse-events-are-not-received-by-a-wpf-scrollviewer-when-hosted-in-a-winforms-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!