当驻留在WinForms容器中时,WPF ScrollViewer不会接收鼠标事件 [英] Mouse events are not received by a WPF ScrollViewer when hosted in a WinForms container
问题描述
我们有一个WinForms应用程序,正在逐步将其转换为WPF.此时,应用程序的主窗体是一个窗体(WinForms),其中包含WPF中内置的垂直边栏.侧边栏托管在ElementHost控件中.
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.
侧边栏由包含其他控件的ScrollViewer组成.问题在于,当焦点位于WinForms区域中的某个位置并且我在ScrollViewer上使用鼠标滚轮时,它不会滚动.
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.
这与WPF/WinForms集成有关,因为在100%WPF项目中,即使焦点位于另一个控件上,ScrollViewer也会对鼠标滚轮做出反应.
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?
推荐答案
考虑进行消息筛选,并在收到WM_MOUSEWHEEL时,确定鼠标是否位于WPF控件上方.如果是这样,则将消息直接发送到元素"窗口句柄.
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.
类似这样的东西:
System.Windows.Forms.Application.AddMessageFilter( new MouseWheelMessageFilter( YourElementInsideAnElementHost ) );
当您超出范围时,不要忘记调用RemoveMessageFilter
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;
}
}
这篇关于当驻留在WinForms容器中时,WPF ScrollViewer不会接收鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!