4

我需要通过 Handle 在其他窗口中托管我的 WPF UserControl。我尝试使用 HwndSource:

var userControl = new MyUserControl();
var parameters = new HwndSourceParameters();
parameters.WindowStyle = 0x10000000 | 0x40000000;
parameters.SetPosition(5, 5);
parameters.SetSize(300, 300);
parameters.ParentWindow = parentWindowHwnd;
var src = new HwndSource(parameters);
src.RootVisual = userControl;

但在这种情况下,箭头和制表键不起作用。

如果我使用 ElementHost 一切正常:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

var userControl = new UserControl1();
var elementHost = new ElementHost();
elementHost.Child = userControl;
elementHost.Left = 5;
elementHost.Top = 5;
elementHost.Width = 300;
elementHost.Height = 300;

SetParent(elementHost.Handle, parentWindowHwnd);

如何使用 HwndSource 获得全部功能?

4

1 回答 1

0

当您使用 HwndSource 时,您必须为 windows 消息注册一个处理程序。

这可以通过调用来完成:

src.AddHook(this.messageHook);

挂钩必须检查 wm_getdlgcode 消息。

    private IntPtr messageHook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
    {
        switch (msg)
        {
            case WmGetDlgCode:
                {
                    handled = true;
                    return (IntPtr)(DlgcWantChars | DlgcWantTab | DlgcWantArrows | DlgcWantAllKeys);
                }
        }
        return IntPtr.Zero;
    }

通过 Dlgc_WantChars、Dlgc_WantTab、Dlgc_WantArrows 和 Dlgc_WantAllKeys 返回您需要的内容。

检查此消息和代码: http: //msdn.microsoft.com/en-us/library/windows/desktop/ms645425 (v=vs.85).aspx

    private const int WmGetDlgCode = 0x0087;

    private const int DlgcWantChars = 0x0080;

    private const int DlgcWantTab = 0x0002;

    private const int DlgcWantAllKeys = 0x0004;

    private const int DlgcWantArrows = 0x0001;
于 2012-08-07T13:20:13.703 回答