实现HwndHost以在C#WPF中处理MouseMove和MouseWheel

时间:2017-11-07 09:23:46

标签: c# wpf interop hwnd hwndhost

我正在尝试在WPF应用中托管DirectX内容。我从这个链接中学到的是子类 HwndHost并创建自己的WndProc实现以及BuildWindowCore和DestroyWindowCore。 https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-hosting-a-win32-control-in-wpf#implement-a-class-to-host-the-microsoft-win32-control

然后,我在这里发现了非常有用的实现: https://github.com/Smartrak/WpfSharpDxControl/blob/master/WpfSharpDxControl/Win32HwndControl.cs

现在,我需要实现另外两个方法,例如WM_MOUSEMOVE(0x0200)和WM_MOUSEWHEEL(0x020A)。 我不确定如何正确地传递鼠标滚轮增量和时间戳等信息。 这方面的任何指针都会有所帮助。

protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case NativeMethods.WM_MOUSEMOVE:
                //What should go here
                break;
            case NativeMethods.WM_MOUSEWHEEL:
                //What should go here
                break;
            case NativeMethods.WM_LBUTTONDOWN:
                RaiseMouseEvent(MouseButton.Left, Mouse.MouseDownEvent);
                break;

            case NativeMethods.WM_LBUTTONUP:
                RaiseMouseEvent(MouseButton.Left, Mouse.MouseUpEvent);
                break;

            case NativeMethods.WM_RBUTTONDOWN:
                RaiseMouseEvent(MouseButton.Right, Mouse.MouseDownEvent);
                break;

            case NativeMethods.WM_RBUTTONUP:
                RaiseMouseEvent(MouseButton.Right, Mouse.MouseUpEvent);
                break;
        }

        return base.WndProc(hwnd, msg, wParam, lParam, ref handled);
    }

谢谢, 杰

1 个答案:

答案 0 :(得分:1)

我终于在这里找到了答案和确切的实现:

https://github.com/tgjones/gemini/blob/master/src/Gemini/Framework/Controls/HwndWrapper.cs

它完美无缺。如果你得到NativeMethods.GetWheelDeltaWParam的OverFlow异常(Convert.ToInt32(value));

使用 NativeMethods.GetWheelDeltaWParam(Convert.ToInt64(值));

Tim Jones对这个非常棒的github回购和工作充满信任! https://github.com/tgjones