如何:使用 Win32 宿主容器执行命中测试

更新:2007 年 11 月

可以通过为可视化对象提供宿主窗口容器在 Win32 中创建可视化对象。若要为包含的可视化对象提供事件处理,需要处理传递到宿主窗口容器的消息筛选器循环的消息。有关如何在 Win32 窗口中承载可视化对象的更多信息,请参见教程:在 Win32 应用程序中承载 Visual 对象

示例

下面的代码演示如何为用作可视化对象的宿主容器的 Win32 窗口设置鼠标事件处理程序。

// Constant values from the "winuser.h" header file.
internal const int WM_LBUTTONUP = 0x0202,
                   WM_RBUTTONUP = 0x0205;

internal static IntPtr ApplicationMessageFilter(
    IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    // Handle messages passed to the visual.
    switch (message)
    {
        // Handle the left and right mouse button up messages.
        case WM_LBUTTONUP:
        case WM_RBUTTONUP:
            System.Windows.Point pt = new System.Windows.Point();
            pt.X = (uint)lParam & (uint)0x0000ffff;  // LOWORD = x
            pt.Y = (uint)lParam >> 16;               // HIWORD = y
            MyShape.OnHitTest(pt, message);
            break;
    }

    return IntPtr.Zero;
}

下面的示例演示如何设置命中测试来响应捕获特定的鼠标事件。

// Constant values from the "winuser.h" header file.
public const int WM_LBUTTONUP = 0x0202,
                 WM_RBUTTONUP = 0x0205;

// Respond to WM_LBUTTONUP or WM_RBUTTONUP messages by determining which visual object was clicked.
public static void OnHitTest(System.Windows.Point pt, int msg)
{
    // Clear the contents of the list used for hit test results.
    hitResultsList.Clear();

    // Determine whether to change the color of the circle or to delete the shape.
    if (msg == WM_LBUTTONUP)
    {
        MyWindow.changeColor = true;
    }
    if (msg == WM_RBUTTONUP)
    {
        MyWindow.changeColor = false;
    }

    // Set up a callback to receive the hit test results enumeration.
    VisualTreeHelper.HitTest(MyWindow.myHwndSource.RootVisual,
                             null,
                             new HitTestResultCallback(CircleHitTestResult),
                             new PointHitTestParameters(pt));

    // Perform actions on the hit test results list.
    if (hitResultsList.Count > 0)
    {
        ProcessHitTestResultsList();
    }
}

HwndSource 对象表示 Win32 窗口中的 Windows Presentation Foundation (WPF) 内容。HwndSource 对象的 RootVisual 属性的值表示可视化树层次结构中的最顶层节点。

有关使用 Win32 宿主容器对对象进行命中测试的完整示例,请参见使用 Win32 互操作进行命中测试的示例

请参见

概念

可视化层中的命中测试

教程:在 Win32 应用程序中承载 Visual 对象

参考

HwndSource