简体   繁体   English

使用HwndSource在Win32应用程序中托管WPF UserControl

[英]Hosting WPF UserControl in Win32 application using HwndSource

I need to host my WPF UserControl in other window by Handle. 我需要通过Handle在其他窗口中托管我的WPF UserControl。 I've tried to use HwndSource: 我试过使用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;

But in this case arrows and tab keys don't work. 但在这种情况下,箭头和标签键不起作用。

If I use ElementHost everything is OK: 如果我使用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);

How can I get full functionality using HwndSource? 如何使用HwndSource获得完整功能?

When you are using HwndSource you must register a handler for the windows messages. 当您使用HwndSource时,您必须为Windows消息注册处理程序。

this can done by call: 这可以通过电话来完成:

src.AddHook(this.messageHook);

The hook must check for wm_getdlgcode message. 钩子必须检查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;
    }

return via Dlgc_WantChars, Dlgc_WantTab, Dlgc_WantArrows and Dlgc_WantAllKeys what you need. 通过Dlgc_WantChars,Dlgc_WantTab,Dlgc_WantArrows和Dlgc_WantAllKeys返回您需要的内容。

check this for the message and codes: http://msdn.microsoft.com/en-us/library/windows/desktop/ms645425(v=vs.85).aspx 检查此消息和代码: 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM